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).\

Respuesta :

Answer:

// Program segment is written in Java programming language

// Comments are used for explanatory purpose

// Program segment starts here

// Initialise the two in variable to 0

count = 0;

longest =0;

// define the string variable

String myString = new String();

// Check if scanner reference contains string using while iteration

while (input.hasNext()){

// Input string while condition is true

myString = input.next();

// Compare length of string with longest variable

if (myString.length() == longest)

{

// If equal, increment count by 1

count++;

}

// If length of string is greater than longest

else

if (myString.length() > longest)

{

longest = myString.length(); // assign length of string to longest

count = 1; // set count to 1

}

}

// End of code segment

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 + "\nThe length: " + longest + "\nThe count: "+ count);

}

}

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

ACCESS MORE