62.0k views
0 votes
Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of strings and two int variables, count and longest, write the code necessary to examine all the strings in the input source and determine how long the longest string (or strings are). That value should be assigned to longest. The number of strings that are of that length should be assigned to count.

2 Answers

3 votes

Answer:

import java.util.Scanner;

public class LongestString

{

public static void main(String[] args) {

int count = 0, longest = 0;

Scanner input = new Scanner(System.in);

Scanner in = new Scanner(System.in);

System.out.print("Enter the size: ");

int size = in.nextInt();

String words[] = new String[size];

for(int i=0; i<size; i++) {

System.out.print("Enter a word: ");

words[i] = input.nextLine();

}

String longestWord = words[0];

for(int i=0; i<size; i++) {

if (words[i].length() > longestWord.length()) {

longestWord = words[i];

longest = words[i].length();

count = 1;

}

else if (words[i].length() == longestWord.length()) {

longest = words[i].length();

count++;

}

}

System.out.println("The longest word: " + longestWord + "\\The length: " + longest + "\\The count: "+ count);

}

}

Step-by-step explanation:

I provided the full code, getting the inputs and print the results, in addition to your request, so that it may be more clear.

-Ask the user for the array size of words, holds the strings entered by the user

- Inside the first for loop, initialize the words array

- Inside the second for loop, find the longest string, its length and the count of the string.

- Print the longest string, its length and count

User Alexxx
by
5.1k points
1 vote

Answer:

count = 0;

longest =0;

String myString = new String();

while (input.hasNext()){

myString = input.next();

if (myString.length() == longest) count++;

else

if (myString.length() > longest){

longest = myString.length();

count = 1;

}

}

Step-by-step explanation:

User Abagshaw
by
4.7k points