简体   繁体   中英

Why is my String not outputting my value correctly?

I Have a simple program where I just prompt to enter an item and the while loop will continue to ask until I enter the word "end" then it will end the program. When I enter a word like so: 在此处输入图片说明

it looks fine, But when I enter 2 words for an item as such I get this output: 在此处输入图片说明

notice how when i entered "green yellow" It prompted me after that to enter an item twice? I can't figure out why it is doing so?

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

    }

}

The default behavior of Scanner is to use whitespace as a delimiter which will be used to break input into tokens. If you just want to use the newline character as a delimiter, try to set the delimiter explicitly.

    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

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

By default it uses any whitespace as the delimiter. So, the call to sc.next() already has its answer with the input green yellow .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM