试图在Java中打破while循环

时间:2015-07-27 01:50:11

标签: java loops while-loop

我花了最近几个小时在互联网和我的Java书籍上寻找答案,但我终于在这里提出了一个问题。一旦用户输入' DONE',我试图突破while循环,但是当我输入done时,它并没有突破循环。我该如何纠正这个问题。

这是我的代码:

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

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

问题看起来像来自同时从两个读取器读取相同的输入流(以及具有相当多的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

给出以下示例用户数据:

  

DONE
  Hello World!
  Java很简单。
  是时候挤出虫子了   做
  做
  lol nope

这是您的代码在第一个nextLine()调用中逐行执行的操作。

首先从流中读取(循环前,input = scan.nextLine();
发生了什么:input = "DONE";
第一行,&#34; DONE&#34;从输入流中删除并分配给input。 <{1}}以前的值,(空字符串)丢失。

从流中读取第二个(循环,input
发生了什么:input = scan.nextLine();
第二行,&#34; Hello World!&#34;从输入流中删除并分配给input = "Hello World!";input之前的值input已丢失。

从流中读取第三个(循环,DONE
发生了什么:input = br.readLine();
第三行,&#34; Java是kool。&#34;从输入流中删除并分配给input = "Java is kool.";input以前的值,&#34; Hello World!&#34;失去了。

输出到标准输出流(循环,input
发生了什么:System.out.println(input);
第三行,&#34; Java是kool。&#34;打印到标准输出流(System.out)。

第四次从流中读取(循环,System.out.println("Java is kool.");
发生了什么:input = scan.nextLine();
第四行,&#34;时间来消灭错误。&#34;从输入流中删除并分配给input = "Time to squash bugs.";input以前的值,&#34; Java是kool&#34;失去了。

equalsIgnoreCase(String)调用赋值结果(循环,input
发生了什么:(input = scan.nextLine()).equalsIgnoreCase("DONE")
第四行输入,&#34;时间来消除错误。&#34;进行测试以查看字符串是否相等,忽略所有大小写。它们不是,因此跳过"Time to squash bugs.".equalsIgnoreCase("DONE")块。没有if因此在else块之后继续执行代码。

结束循环。此时没有任何东西强行终止循环,因此执行会回到循环的状态。条件(if)允许循环执行,因此它再次从顶部开始。

第五次从流中读取(循环,true
发生了什么:input = scan.nextLine();
第五行,&#34;完成&#34;从输入流中删除并分配给input = "Done";input以前的值,&#34;时间来压缩错误。&#34;失去了。

从流中读取第六个(循环,input
发生了什么:input = br.readLine();
第六行,&#34; dONe&#34;从输入流中删除并分配给input = "dONe";input以前的值,&#34;完成&#34;失去了。

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

从流中读取第七个(循环,System.out.println("dONe");
发生了什么:input = scan.nextLine();
第七行,&#34; lol nope&#34;从输入流中删除并分配给input = "lol nope";input之前的值,&#34; dONe&#34;失去了。

equalsIgnoreCase(String)调用赋值结果(循环,input
发生了什么:(input = scan.nextLine()).equalsIgnoreCase("DONE")
第七行输入,&#34; lol nope&#34;进行测试以查看字符串是否相等,忽略所有大小写。它们不是,因此跳过"lol nope".equalsIgnoreCase("DONE")块。没有if因此在else块之后继续执行代码。

结束循环。此时没有任何东西强行终止循环,因此执行会回到循环的状态。条件(true)允许循环执行,因此它再次从顶部开始。


在示例输入中,在&#34; lol nope&#34;之后没有更多输入。所以下一次调用if块并且程序冻结,在输入之前无法执行任何操作。通过当前设置代码的方式,只有第四行用户输入之后的第三行(并包括)才会被读入并检查是否与#34; DONE&#34;相等。

  

DONE
  Hello World!
  Java很简单。
  是时候挤出虫子了。
  做
  做
   lol nope

首先修复:完全删除变量scan.nextLine()isr,然后使用br(反之亦然,摆脱scan并使用scanisr)。由于他们从同一输入流中提取数据,因此他们以相同的方式执行相同的工作,从而创建不必要且令人困惑的代码。

第二个修复:如果您在调用readLine()或nextLine()之间没有对输入变量执行任何操作,并且您没有使用这些调用来消除垃圾输入数据,那么就可以获取它们。您调用readLine()或nextLine()一次并将其存储到br,该值将一直保留到input的下一个分配。

如果您实际上正在使用readLine()或nextLine()的多个调用来检索用户数据,但该数据可能包括&#34; DONE&#34;然后你需要用你的if块替换对readLine()或nextLine()的调用,因为它读取输入并立即检查它是否等于&#34; DONE&#34;。

根据您的需求,可能会对您的代码进行一些修复(我假设您修剪的代码没有被认为是相关的,或者根本没有添加。)

input

此外:

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"
                    + "");
        }
    }
}

答案 1 :(得分:0)

您将扫描仪缠绕在阅读器周围,然后同时尝试从两个阅读器中读取,这使得它们可以在可用输入上进行争夺。直接从阅读器中消除读取。

答案 2 :(得分:0)


我建议您先尝试使用此版本的缩减版,然后尝试在文件中添加所需的全部内容。

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!!");
    }
}