gpt4 book ai didi

java - 尝试打破Java中的while循环

转载 作者:行者123 更新时间:2023-12-01 11:17:25 26 4
gpt4 key购买 nike

我花了最后几个小时在互联网和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”,并将其分配给 inputinput的先前值(空字符串)丢失。

从流中进行第二次读取(循环中, input = scan.nextLine();
发生了什么: input = "Hello World!";
第二行,“ Hello World!”从输入流中删除并分配给 inputinput的先前值 DONE丢失。

从流中三次读取(循环中, input = br.readLine();
发生了什么: input = "Java is kool.";
第三行,“ Java是愚人”。从输入流中删除并分配给 inputinput的先前值“ Hello World!”迷路了。

输出到标准输出流(循环, System.out.println(input);
发生了什么: System.out.println("Java is kool.");
第三行,“ Java是愚人”。打印到标准输出流(System.out)。

从流中第四次读取(循环中, input = scan.nextLine();
发生了什么: input = "Time to squash bugs.";
第四行,“压缩错误的时间”。从输入流中删除并分配给 inputinput的先前值“ 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";
从输入流中删除第五行“完成”,并将其分配给 inputinput的先前值“压扁错误的时间”。迷路了。

从流中第六次读取(循环中, input = br.readLine();
发生了什么: input = "dONe";
第六行“ dONe”从输入流中删除,并分配给 inputinput的先前值“ Done”丢失。

输出到标准输出流(循环, System.out.println(input);
发生了什么: System.out.println("dONe");
第六行“ dONe”被打印到标准输出流(System.out)。

从流中第七次读取(循环中, input = scan.nextLine();
发生了什么: input = "lol nope";
从输入流中删除第七行“ lol nope”,并将其分配给 inputinput的先前值“ 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


第一个解决方案:完全删除变量 isrbr并仅使用 scan(反之亦然,删除变量 scan并使用 isrbr)。由于他们从相同的输入流中提取数据,因此它们以几乎相同的方式完成相同的工作,从而创建了不必要的且令人困惑的代码。

第二种解决方法:如果您在两次调用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"
+ "");
}
}
}

关于java - 尝试打破Java中的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31643884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com