簡體   English   中英

嘗試打破Java中的while循環

[英]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

首先修復:擺脫變量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"
                    + "");
        }
    }
}

您正在將掃描儀包裹在閱讀器上,然后嘗試同時讀取它們,這使它們在可用輸入之間進行爭奪。 直接消除閱讀器中的讀物。


我建議您首先嘗試使用實施的簡化版本,然后再嘗試將所需的所有內容添加到文件中。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM