Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

前端 未结 12 1348
灰色年华
灰色年华 2020-12-01 10:18

How does this program actually work...?

import java.util.Scanner;

class string
{
    public static void main(String a[]){
        int a;
        String s;
          


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

    You only need to use scan.next() to read a String.

    0 讨论(0)
  • 2020-12-01 10:24

    Incase you don't want to use nextint, you can also use buffered reader, where using inputstream and readline function read the string.

    0 讨论(0)
  • 2020-12-01 10:25

    if you don't want to use parser :

    int a;
    String s;
    Scanner scan = new Scanner(System.in);
    
    System.out.println("enter a no");
    a = scan.nextInt();
    System.out.println("no is =" + a);
    scan.nextLine(); // This line you have to add (It consumes the \n character)
    System.out.println("enter a string");
    s = scan.nextLine();
    System.out.println("string is=" + s);
    
    0 讨论(0)
  • 2020-12-01 10:25

    Simple solution to consume the \n character:

    import java.util.Scanner;
    class string
    {
        public static void main(String a[]){
            int a;
            String s;
            Scanner scan = new Scanner(System.in);
    
            System.out.println("enter a no");
            a = scan.nextInt();
            System.out.println("no is ="+a);
    
            scan.nextLine();
            System.out.println("enter a string");
            s = scan.nextLine();
            System.out.println("string is="+s);
        }
    }
    
    0 讨论(0)
  • 2020-12-01 10:27

    This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:

    1. You can use another nextLine() method just after the nextInt() to move the scanner past the newline character.
    2. You can use different Scanner objects for scanning the integer and string (You can name them scan1 and scan2).
    3. You can use the next method on the scanner object as

      scan.next();

    0 讨论(0)
  • 2020-12-01 10:32
     s=scan.nextLine();
    

    It returns input was skipped.

    so you might use

     s=scan.next();
    
    0 讨论(0)
提交回复
热议问题