So I'm a beginner at programming and I'm trying to figure out what the problem is with the
following functions. The problem is with the scan.hasNext()
method I have two println
statements (one right after I make scan, and one on the second method) telling me whether scan.hasNext()
returns true or false. The weird thing is
that the code as it is now enters the while loop which is what should happen, but when I
delete one of the println
statements it doesn't go in the loop and the other print
statement tells me scan.hasNext()
is false.
This is weird because I change nothing except for erasing a print statement. Furthermore I
found if I add one more for a total of 3 print statements it will be false again, and if I
add a fourth it's true again, etc. I think I just don't understand how hasNext works since I
have no idea how to follow where the "cursor" should be.
public void createFile(String filename){
final File file = new File(filename);
try{
scan = new Scanner(file);
**System.out.println(scan.hasNext());**
buff = new BufferedWriter(new FileWriter(filename), 1);
}
catch(Exception e1){
try{
buff = new BufferedWriter(new FileWriter(filename));
scan = new Scanner(file);
}
catch(Exception e2){
System.out.println("Error trying to create file");
}
}
}
public String readFile(){
String fileContents = "";
**System.out.println(scan.hasNext());**
if(scan.hasNext())
while(scan.hasNext())
fileContents = fileContents + scan.next()+" "+scan.next()+" "+scan.next();
return fileContents;
}