Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

后端 未结 22 1089
北荒
北荒 2020-12-03 01:14

I\'m writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say

相关标签:
22条回答
  • 2020-12-03 01:43

    I tried following code but this is not stopping as there is no break condition so it always waiting for input , may be you could add a condition for break

    public class Solution {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int i = scan.nextInt();
            double d = scan.nextDouble();
            String s="";
            while(scan.hasNext())
            {
                s=scan.nextLine();
            }
    
            System.out.println("String: " +s);
            System.out.println("Double: " + d);
            System.out.println("Int: " + i);
        }
    }
    
    0 讨论(0)
  • 2020-12-03 01:43

    next() will only store the input up to the first token. if there are two words "Hi there" it means there are two tokens separated by space (delimiter). Every time you call the next() method it reads only one token.

    if input is "Hi there !"

    Scanner scan = new Scanner(System.in);
    String str = scan.next()
    System.out.println(str);
    

    Output

    Hi

    So if you both the words you need to call next() again to get the next token which is inefficient for longer string input

    nextLine() on the other hand grabs the entire line that the user enters even with spaces

    Scanner scan = new Scanner(System.in);
    String str = scan.nextLine()
    System.out.println(str);
    

    Output

    Hi there !

    0 讨论(0)
  • 2020-12-03 01:44

    Initialize the Scanner this way so that it delimits input using a new line character.

    Scanner sc = new Scanner(System.in).useDelimiter("\\n");
    

    Refer the JavaDoc for more details

    Use sc.next() to get the whole line in a String

    0 讨论(0)
  • 2020-12-03 01:45

    Instead of using System.in and System.out directly, use the Console class - it allows you to display a prompt and read an entire line (thereby fixing your problem) of input in one call:

    String address = System.console().readLine("Enter your Address: ");
    
    0 讨论(0)
  • 2020-12-03 01:45

    next() is read until the space of the encounter, and the nextLine() is read to the end of the line. Scanner scan = new Scanner(System.in);
    String address = scan.next();
    s += scan.nextLine();

    0 讨论(0)
  • 2020-12-03 01:48
    String s="Hi";
    String s1="";
    
    //For Reading Line by hasNext() of scanner 
     while(scan.hasNext()){
      s1 = scan.nextLine();
     }
    System.out.println(s+s1);
    
    /*This Worked Fine for me for reading Entire Line using Scanner*/
    
    0 讨论(0)
提交回复
热议问题