[英]Attempting to break a while loop in Java
我花了最后几个小时在互联网和Java书籍中搜索答案,但最终我还是在这里发布了一个问题。 一旦用户输入“ DONE”,我试图打破while循环,但是当我输入完成时,它并没有脱离循环。 我该如何解决这个问题。
这是我的代码:
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
// Name of the file
String fileName = "userStrings.txt";
Scanner scan = new Scanner(System.in);
try {
// FileReader reading the text files in the default encoding.
FileWriter fileWriter = new FileWriter("userStrings.txt");
// Wrapping FileReader in BufferedReader.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
PrintWriter outFile = new PrintWriter (bufferedWriter);
// InputStreamReader & BufferedReader for user input
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = "";
System.out.print("Enter something (DONE to quit): ");
input = scan.nextLine();
while (true) {
System.out.println("Enter something else or DONE to quit: ");
input = scan.nextLine();
input = br.readLine();
System.out.println(input);
if ((input = scan.nextLine()).equalsIgnoreCase("DONE")){
break;
}
}
bufferedWriter.write(input);
// Closing file
bufferedWriter.close();
}
catch (IOException ex){
System.out.println("Error writing to file " + "userStrings.txt" + "");
}
} // End of method header
} // End of class header
谢谢您的帮助!
该问题似乎来自于同时从两个读取器读取相同的输入流(以及有相当多的readLine()调用)
这是您的代码中出现的错误:
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
String fileName = "userStrings.txt";
// Here you create a scanner using Standard Input as the input
// stream. (This is fine)
Scanner scan = new Scanner(System.in);
try {
// You say this is a FileREADER though it is clearly not...
// fix this comment!
// Either have remotely correct comments or just remove them.
FileWriter fileWriter = new FileWriter("userStrings.txt");
// Once again these are WRITERS not READERS.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
PrintWriter outFile = new PrintWriter(bufferedWriter);
// Despite bad comments, the above code is NOT a problem.
// You just created a scanner, using it for input.
// Why make a second object to read from the SAME input stream?
// Not only does this cause confusion in how the stream is handled,
// but its useless code when you already have a Scanner.
// Remove these two objects and all references to them and
// replace them with the Scanner reference (or vice versa).
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
// Setting to emptyquotes is useless unless you are using the
// variable before its next write. Still, not the error.
String input = "";
System.out.print("Enter something (DONE to quit): ");
// Begin problems. You are reading in a line here,
// and once again, YOU ARE DOING >NOTHING< with it
// before the next write. In your print you say
// "DONE to quit" but you are NOT checking if
// input.equals("DONE")
input = scan.nextLine();
while (true) {
System.out.println("Enter something else or DONE to quit: ");
// Stream Read number 2, variable write number 3, still you
// have not READ from the input variable.
input = scan.nextLine();
// Stream Read number 3, variable write number 4, still you
// have not READ from the input variable.
// Also, despite you using a different reader, this is still
// accessing and pulling data out of the same input stream.
// Whatever the Scanner has pulled out is no longer in the
// input stream.
input = br.readLine();
// Finally you are reading the string in the variable
// 'input'. On the first iteration of the while loop you
// will have written to input 3 times already. You will
// only be printing the 3RD LINE of input from the user.
// Still however, you are not checking if
// input.equals("DONE") which is supposed to be the
// condition terminating your loop.
System.out.println(input);
// Stream read number 4, variable write number 5, FINALLY
// checking the user's input against the string "DONE" and
// terminating the loop. On the first iteration of the loop,
// this stream read will only see the 4TH line of input from
// the user.
if ((input = scan.nextLine()).equalsIgnoreCase("DONE")) {
break;
}
}
bufferedWriter.write(input);
// Closing file
bufferedWriter.close();
}
catch (IOException ex) {
System.out.println("Error writing to file " + "userStrings.txt"
+ "");
}
} // End of method header
} // End of class header
给定以下示例用户数据:
完成
你好,世界!
Java是愚蠢的。
是时候来压缩漏洞了。
完成
堂
哈哈nope
这是您的代码从第一个nextLine()调用逐行执行的操作。
首先从流中读取(在循环之前, input = scan.nextLine();
)
发生了什么: input = "DONE";
从输入流中删除第一行“ DONE”,并将其分配给input
。 input
的先前值(空字符串)丢失。
从流中进行第二次读取(循环中, input = scan.nextLine();
)
发生了什么: input = "Hello World!";
第二行,“ Hello World!” 已从输入流中删除并分配给input
。 input
的先前值DONE
丢失。
从流中进行第三次读取(循环中, input = br.readLine();
)
发生了什么: input = "Java is kool.";
第三行,“ Java是愚人”。 已从输入流中删除并分配给input
。 input
的先前值“ Hello World!” 迷路了。
输出到标准输出流(循环, System.out.println(input);
)
发生了什么: System.out.println("Java is kool.");
第三行,“ Java是愚人”。 打印到标准输出流(System.out)。
从流中第四次读取(循环中, input = scan.nextLine();
)
发生了什么: input = "Time to squash bugs.";
第四行,“压缩错误的时间”。 已从输入流中删除并分配给input
。 input
的先前值“ Java is kool”丢失。
对赋值结果调用equalsIgnoreCase(String)(循环中, (input = scan.nextLine()).equalsIgnoreCase("DONE")
)
发生了什么事: "Time to squash bugs.".equalsIgnoreCase("DONE")
输入的第四行是“压缩错误的时间”。 被测试以查看字符串是否相等,而忽略所有大写字母。 它们不是,因此跳过if
块。 没有else
因此代码执行在if
块之后继续。
循环结束。 在这一点上,没有任何东西可以强制终止循环,因此执行可以返回到循环的条件。 条件( true
)允许循环执行,因此它再次从顶部开始。
从流中第五次读取(循环中, input = scan.nextLine();
)
发生了什么: input = "Done";
第五行“完成”已从输入流中删除,并分配给input
。 input
的先前值“压缩错误的时间”。 迷路了。
从流中第六次读取(循环中, input = br.readLine();
)
发生了什么: input = "dONe";
第六行“ dONe”从输入流中删除,并分配给input
。 input
的先前值“ Done”丢失。
输出到标准输出流(循环, System.out.println(input);
)
发生了什么: System.out.println("dONe");
第六行“ dONe”被打印到标准输出流(System.out)。
从流中读取第七次(循环中, input = scan.nextLine();
)
发生了什么: input = "lol nope";
第七行“哈哈nope”从输入流中删除,并分配给input
。 input
的先前值“ dONe”丢失。
对赋值结果调用equalsIgnoreCase(String)(循环中, (input = scan.nextLine()).equalsIgnoreCase("DONE")
)
发生了什么: "lol nope".equalsIgnoreCase("DONE")
输入的第七行“ lol nope”被测试以查看字符串是否相等,而忽略所有大写字母。 它们不是,因此跳过if
块。 没有else
因此代码执行在if
块之后继续。
循环结束。 在这一点上,没有任何东西可以强制终止循环,因此执行可以返回到循环的条件。 条件(true)允许循环执行,因此它再次从顶部开始。
在示例输入中,“ lol nope”之后没有更多输入,因此对scan.nextLine()
的下一次调用将阻塞,程序将冻结,直到有输入才无法执行任何操作。 通过当前设置代码的方式,仅会读入用户输入的第四行(包括第四行)之后的第三行,并检查与“ DONE”是否相等。
完成
你好,世界!
Java是愚蠢的。
是时候来压缩漏洞了。
完成
堂
哈哈nope
首先修复:摆脱变量isr
和br
干脆只使用scan
(或相反,摆脱了scan
,并使用isr
和br
)。 由于他们从相同的输入流中提取数据,因此它们以几乎相同的方式完成相同的工作,从而创建了不必要的且令人困惑的代码。
第二种解决方法:如果您在两次调用readLine()或nextLine()之间没有使用输入变量做任何事情,并且没有在使用这些调用来消除垃圾输入数据,请清除它们。 您只需调用一次readLine()或nextLine()并将其存储到input
,该值将一直保留到下一次分配给input
为止。
如果您实际上使用了多次调用readLine()或nextLine()来检索用户数据,但该数据可能包含“ DONE”,则您需要用if块替换对readLine()或nextLine()的调用,因为它会读取输入并立即检查是否等于“ DONE”。
根据您的需求,对代码进行一些可能的修复(我假设您修剪了一些您认为不相关的代码,或者只是尚未添加代码而已。)
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
String fileName = "userStrings.txt";
Scanner scan = new Scanner(System.in);
try {
FileWriter fileWriter = new FileWriter("userStrings.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
PrintWriter outFile = new PrintWriter(bufferedWriter);
String input;
System.out.print("Enter something (DONE to quit): ");
if (!(input = scan.nextLine()).equalsIgnoreCase("DONE")) { // Added "!" (not)
// Some one time use code goes here.
System.out.println("Enter something else or DONE to quit: ");
while (true) {
if ((input = scan.nextLine()).equalsIgnoreCase("DONE")) {
break;
}
// Some code goes here
if ((input = scan.nextLine()).equalsIgnoreCase("DONE")) {
break;
}
// Some DIFFERENT code goes here.
System.out.println(input);
if ((input = scan.nextLine()).equalsIgnoreCase("DONE")) {
break;
}
// Some code that didn't belong above can go here.
}
}
bufferedWriter.write(input);
bufferedWriter.close();
}
catch (IOException ex) {
System.out.println("Error writing to file " + "userStrings.txt"
+ "");
}
}
}
也:
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
String fileName = "userStrings.txt";
Scanner scan = new Scanner(System.in);
try {
FileWriter fileWriter = new FileWriter("userStrings.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
PrintWriter outFile = new PrintWriter(bufferedWriter);
String input;
System.out.print("Enter something (DONE to quit): ");
if (!(input = scan.nextLine()).equalsIgnoreCase("DONE")) { // Added "!" (not)
// Some one time use code goes here.
System.out.println("Enter something else or DONE to quit: ");
while ((input = scan.nextLine()).equalsIgnoreCase("DONE")) {
System.out.println(input);
// Some code can go here.
}
}
bufferedWriter.write(input);
bufferedWriter.close();
}
catch (IOException ex) {
System.out.println("Error writing to file " + "userStrings.txt"
+ "");
}
}
}
或者,如果您希望所有代码在循环中运行:
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
String fileName = "userStrings.txt";
Scanner scan = new Scanner(System.in);
try {
FileWriter fileWriter = new FileWriter("userStrings.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
PrintWriter outFile = new PrintWriter(bufferedWriter);
String input;
System.out.print("Enter something (DONE to quit): ");
while ((input = scan.nextLine()).equalsIgnoreCase("DONE")) {
System.out.println(input);
// Some code can go here.
System.out.println("Enter something else or DONE to quit: ");
}
bufferedWriter.write(input);
bufferedWriter.close();
}
catch (IOException ex) {
System.out.println("Error writing to file " + "userStrings.txt"
+ "");
}
}
}
您正在将扫描仪包裹在阅读器上,然后尝试同时读取它们,这使它们在可用输入之间进行争夺。 直接消除阅读器中的读物。
我建议您首先尝试使用实施的简化版本,然后再尝试将所需的所有内容添加到文件中。
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.print("Enter something (DONE to quit): ");
input = scan.nextLine();
System.out.println(input);
while (!input.equalsIgnoreCase("DONE")) {
System.out.println("Enter something else or DONE to quit: ");
input = scan.nextLine();
System.out.println(input);
}
scan.close();
System.out.println("DONE!!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.