Scanner only reads first word instead of line

后端 未结 5 1706
清歌不尽
清歌不尽 2020-12-17 15:58

In my current program one method asks the user to enter the description of a product as a String input. However, when I later attempt to print out this informat

相关标签:
5条回答
  • 2020-12-17 16:39

    Replace next() with nextLine():

    String productDescription = input.nextLine();
    
    0 讨论(0)
  • 2020-12-17 16:40

    Javadoc to the rescue :

    A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace

    nextLine is probably the method you should use.

    0 讨论(0)
  • 2020-12-17 16:41

    The javadocs for Scanner answer your question

    A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

    You might change the default whitespace pattern the Scanner is using by doing something like

    Scanner s = new Scanner();
    s.useDelimiter("\n");
    
    0 讨论(0)
  • 2020-12-17 16:50

    input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try input.nextLine().

    0 讨论(0)
  • 2020-12-17 16:52

    Use input.nextLine(); instead of input.next();

    0 讨论(0)
提交回复
热议问题