Reputation: 391
import java.io.*;
import java.util.*;
public class Hellno {
public static void main(String[] args) {
try {
Scanner s = new Scanner(new File("words.txt"));
findBiggest(s);
System.out.println(findBiggest(s));
} catch (IOException e) {
System.out.println("Can't find that file");
}
}
public static String findBiggest(Scanner scan) {
int count0 = 0;
int count1 = 0;
String srs = "";
while (scan.hasNext()) { //how do i make this the longest?
String nsrs = scan.next();
count0 = nsrs.length();
if (count0 > count1) { // if the new length is bigger than what was solidified
count1 = count0; //new solidification of number
count0 = 0; // count becomes 0 to start again
srs = nsrs; // nsrs has been solidified as the new biggest String
}
else if (count0 <= count1) { // if the new length is smaller than what was solidified
count0 = 0; //then we start again with dummyCount = 0;
}
}
return srs;}}
I am trying to read from a text file, find out what is the longest string and return that string. However, this coding ignores all of while() and seems to jump to return srs. Why??
Upvotes: 0
Views: 201
Reputation: 2040
need to set a delimiter on the scanner
Scanner s = new Scanner(input).useDelimiter(System.getProperty("line.separator"));
Upvotes: 0
Reputation: 178253
You are calling findBiggest
twice on the same Scanner
. The first call presumably finds the biggest word and returns it, but it's ignored. The second call finds no words, and the while
loop has no iterations.
Just call findBiggest
once.
Scanner s = new Scanner(new File("words.txt"));
System.out.println(findBiggest(s));
Upvotes: 6