所以我是第一次程序员,我的循环遇到了问题,我似乎无法弄清楚我做错了什么。下面的代码应该获取用户输入的文本文件的位置,如果正确,则不会出现错误消息,但如果不正确,则应弹出错误消息“文件位置不正确”,并且用户可以输入正确的位置。但发生的情况是错误消息不断弹出,直到我终止程序。谁能给我一些关于我做错了什么的建议?
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");
}
}
}
}
最佳答案
这里有两个主要问题。
首先,您编写了 while(flag = true)
,这意味着“将值 true 分配给 flag,然后如果 flag 的结果值为 true,则继续循环”。这样的循环不会退出(除非您在循环内调用 break
)。
您的意思可能是 while(flag == true)
(注意使用两个等号),它表示“检查 flag 的值是否为 true,如果是则继续循环”。您也可以说 while(flag)
。
第二个问题是在进入 while 循环之前提示用户输入,因此每次循环迭代只查看第一次给出的相同输入。要解决此问题,请移动提示(并读取)用户输入的代码。它应该位于循环的顶部,而不是循环之前。也就是说,而不是
// prompt for input
// read input
while (flag == true) {
// ....
}
你应该有
while (flag == true) {
// prompt for input
// read input
// ...
}
关于Java,用户输入文件位置循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224093/