I am reading from a file and storing them into an array....
f = new File("some file");
try {
s = new Scanner(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String theWord [] = new String[100];.
while(s.hasNext()){
int i=0;
theWord[i]=s.next();
//print
System.out.println(theWord[i]);
i++;
}
System.out.println(theWord[0]);
System.out.println(theWord[1]);
Say the file has the words: Hello Programmer. The output is:
Hello
programmer
programmer
null
THe last two lines are puzzling me. It shows that the 0 index of theWord is programmer and 1 index is null when just before the zero index should be hello and the 1 index should be programmer.
Any help?
You need to move:
int i=0;
Outside the loop. You always update theWord[0]
value.
You are re-initializing i
to 0
in your while
loop, so every time, the 0 th element of your array is overwritten.
while(s.hasNext()){
int i=0; // Move this outside the while loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.