General Antrhax General Antrhax - 1 month ago 11
Java Question

Java, user entered file location loop

So I'm a first time programmer and I'm having problem with my loop and for the life of me I can't seem to figure out what I'm doing wrong. The code below is supposed to take the user entered location of the text file and if its correct it should there will be no error message but if its incorrect the error message "Incorrect file location" should pop and the user can input the correct location. But what happens is the error message pops up keeps popping up until I terminate the program. Can anyone give me some advice with what I'm doing wrong?

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadingText {

public static void main(String [] args ){
System.out.println("Input the full path to the text file location: ");

Scanner keyboardInput = new Scanner(System.in);
String userFileLocation = keyboardInput.nextLine();
File s = new File(userFileLocation);
boolean flag = false;

while(flag = true)
{

try
{
Scanner sc = new Scanner (s);
while(sc.hasNext())
{

}
}catch ( FileNotFoundException e )
{
System.out.println("Incorrect File Location");
}


}
}


}

Answer

There are two main problems here.

First, you wrote while(flag = true), which means "assign the value true to flag, and then continue looping if the resulting value of flag is true". Such a loop won't exit (unless you call break from within the loop).

You probably meant while(flag == true) (note the use of two equal signs), which says "check if the value of flag is true, and continue looping if it is". You could just as well say while(flag).

The second problem is that you prompt the user for input before entering the while loop, so each loop iteration just looks at the same input that was given the very first time. To fix this, move the code that prompts for (and reads) the user's input. Instead of before the loop, it should be at the top of the loop. That is, instead of

// prompt for input
// read input
while (flag == true) {
    // ....
}

you should have

while (flag == true) {
    // prompt for input
    // read input
    // ...
}