Could you please help me to solve the following JAVA problem? I really appreciat
ID: 3874693 • Letter: C
Question
Could you please help me to solve the following JAVA problem? I really appreciate your help.
Q1 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 string that are of that length should be assigned to count
DAN
Explanation / Answer
import java.io.File;
import java.util.Scanner;
/**
* @author
*
*/
public class CountData {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("data.txt"));
int count, longest;
// read count and longest values from scanner
count = scanner.nextInt();
longest = scanner.nextInt();
while (scanner.hasNext()) {
// read the word
String string = scanner.next();
// checking the string length
if (longest < string.length()) {
longest = string.length();
count = 0;
} else {
count++;
}
}
// print the values of longest and count
System.out.println("Longest String:" + longest);
System.out.println("Count :" + count);
} catch (Exception e) {
// TODO: handle exception
}
}
}
data.txt
5 8
beef and pork next yeer, the government said Wednesdaay, as consumers bear some of the bruntt of the sweltering heat that is drivng up the cost of feed corrn.
OUTPUT:
Longest String:11
Count :20
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.