为什么我的String没有正确输出我的值?

时间:2014-05-02 23:39:56

标签: java

我有一个简单的程序,我只是提示输入一个项目,而while循环将继续询问,直到我输入单词“end”然后它将结束程序。当我输入这样的单词时:enter image description here

它看起来很好,但是当我为一个项目输入2个单词时,我得到了这个输出: enter image description here

注意当我输入“绿色黄色”时,它之后是否提示我两次输入项目? 我无法弄清楚为什么会这样做?

    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();

    }

}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

请参阅http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

默认情况下,它使用任何空格作为分隔符。因此,对sc.next()的调用已经有了输入green yellow的答案。