i trying read data text file , store array. assume there 1 word per line. getting nosuchelementexception
here:
while (s.hasnextline()) { text = text + s.next() + " "; }
this code:
public class readnote { public static void main(string[]args) { string text = readstring("countrylist.txt"); system.out.println(text); string[] words = readarray("countrylist.txt"); (int = 0; < words.length; i++) { system.out.println(words[i]); } } public static string readstring(string file) { string text = ""; try{ scanner s = new scanner(new file(file)); while (s.hasnextline()) { text = text + s.next() + " "; } } catch(filenotfoundexception e) { system.out.println("file not found "); } return text; } public static string[] readarray(string file) { int ctr = 0; try { scanner s1 = new scanner(new file(file)); while (s1.hasnextline()) { ctr = ctr+1; s1.next(); } string[] words = new string[ctr]; scanner s2 = new scanner(new file(file)); ( int = 0; < ctr; i++) { words [i] = s2.next(); } return words; } catch (filenotfoundexception e) { } return null; } }
here message.
exception in thread "main" java.util.nosuchelementexception @ java.util.scanner.throwfor(scanner.java:862) @ java.util.scanner.next(scanner.java:1371) @ readnote.readstring(readnote.java:29) @ readnote.main(readnote.java:13)
for specific exception getting in readstring
:
while (s.hasnextline()) { text = text + s.next() + " "; }
you need either call s.hasnext()
in loop guard, or use s.nextline()
in body.
Comments
Post a Comment