簡體   English   中英

我如何在while循環中使用條件字符串?

[英]How do I use a string conditional in a while loop, java?

public class Diary {
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        PrintWriter output = null;
        try {
            output = new PrintWriter (new FileOutputStream("diaryLog"));
        } catch (FileNotFoundException e) {
             System.out.println("File not found");
             System.exit(0);
        }

        //Ok, I will ask the date for you here:
        System.out.println("Enter the date as three integers separated by spaces (i.e mm dd yyyy):");
        int month = input.nextInt();
        int day = input.nextInt();
        int year = input.nextInt();

        //And print it in the file
        output.println("Date: " + month +"/" + day + "/" + year);
        System.out.println("Begin your entry:");
        String entry= input.next();
        while("end".equals(entry))
        {
        output.print(entry + " ");
        }

        output.close();
        System.out.println("End of program.");
       }
 }

該程序的目標是輸入並創建一個日記條目,並在輸入單詞end時將輸入輸出到文件中。 當我編譯時,當我輸入end並且我的日記條目未保存在輸出文件中時,程序不會終止。

在您的代碼中,如果entry值為end則循環將繼續。 但是,您想要反向操作,請使用! 運營商。 同樣,您也沒有在循環內使用新值重新分配entry ,因此,如果條目的第一個值本身是end ,將導致無限循環。

您需要將值重新分配給entry

String entry;
while(!"end".equals(entry = input.next())) {// I had used `!` logical operator
    output.print(entry + " ");
}

在循環的每次迭代中,您都希望任務用戶更多的輸入。 因為您想讓用戶至少輸入一次內容,所以應該使用do-while循環,例如...

String entry = null;
do {
    entry = input.nextLine();
} while (!"end".equals(entry));

有幾處更改。 您應該擁有的是:

 String entry= input.next();
    output.print(entry + " ");
    while(! "end".equals(entry))
    {

        entry= input.next();
    }

    output.close();
    System.out.println("End of program.");

意圖是,當用戶不輸入“ end”時繼續閱讀。

上面給出的解決方案是正確的,但不要忘記關閉input否則,在Eclipse中,當您嘗試打開文本文件時,將遇到堆大小問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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