I am trying to read data from a text file and then store it to an array. I assume that there is one word per line. I am getting a NoSuchElementException
here:
while (s.hasNextLine())
{
text = text + s.next() + " ";
}
This is my code:
public class ReadNote
{
public static void main(String[]args)
{
String text = readString("CountryList.txt");
System.out.println(text);
String[] words = readArray("CountryList.txt");
for (int i = 0; i < 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));
for ( int i = 0; i < ctr; i++)
{
words [i] = s2.next();
}
return words;
} catch (FileNotFoundException e) { }
return null;
}
}
Here is the message.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ReadNote.readString(ReadNote.java:29)
at ReadNote.main(ReadNote.java:13)