簡體   English   中英

為什么我的String無法正確輸出我的值?

[英]Why is my String not outputting my value correctly?

我有一個簡單的程序,我只是提示輸入一個項目,而while循環將繼續詢問,直到我輸入單詞“ end”,然后程序才會結束。 當我輸入這樣的詞時: 在此處輸入圖片說明

看起來不錯,但是當我為一個項目輸入2個單詞時,我得到以下輸出: 在此處輸入圖片說明

請注意,當我輸入“綠色黃色”時,如何提示我輸入兩次? 我不知道為什么要這么做?

    import java.util.Scanner;


public class ToDoListapp {

    public static void main(String[] args) /*throws IOException*/ {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);

        System.out.println("Welome to your TodoList");
        boolean keepAdd = true;
        String item;

        //file
        //PrintWriter writeFile = new PrintWriter("TodoList.txt", "UTF-8");


        //  File file = new File("ToDo.txt");
        //  BufferedWriter writeTo = new BufferedWriter(new FileWriter(file));




        while (keepAdd)
        {
            System.out.println("Enter an item: ");
            item = sc.next();

            if (item.equals("end"))
            {
                keepAdd = false;

            }
        //  writeTo.write(item + "\n");



        }
        //writeTo.close();

    }

}

Scanner的默認行為是使用空格作為分隔符,該分隔符將用於將輸入分成令牌。 如果只想將換行符用作分隔符,請嘗試顯式設置分隔符。

    Scanner sc = new Scanner(System.in);
    sc.useDelimiter(System.getProperty("line.separator"));

    System.out.println("Welome to your TodoList");
        boolean keepAdd = true;
        String item;

    // The rest of your code

參見http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

默認情況下,它使用任何空格作為分隔符。 因此,對sc.next()的調用已經有了輸入green yellow答案。

暫無
暫無

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

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