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

后端 未结 22 1107
北荒
北荒 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条回答
  •  萌比男神i
    2020-12-03 01:50

    We can easily done using scan.nextLine .It will read the rest of the input till the end. Then assign it to your variable. Entire sentence can be printed easily . Here is the example for your better understanding.

        String s = "HackerRank ";
    
        Scanner scan = new Scanner(System.in);
    
    
        String s2;
    
    
    
        scan.nextLine(); // read the rest of the line of input (newline character after the double token).
        s2 = scan.nextLine();
    
    
    
        /* Concatenate and print the String variables on a new line integer variables on a new line; 
    
        System.out.println(s + s2);
    
        scan.close();
    

    } }

提交回复
热议问题