user3131148
user3131148

Reputation: 353

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:enter image description here

it looks fine, But when I enter 2 words for an item as such I get this output: enter image description here

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

    }

}

Upvotes: 0

Views: 66

Answers (2)

MarsAtomic
MarsAtomic

Reputation: 10696

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

Upvotes: 2

JoeNahmias
JoeNahmias

Reputation: 305

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.

Upvotes: 1

Related Questions