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

前端 未结 12 1384
灰色年华
灰色年华 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条回答
  •  Happy的楠姐
    2020-12-01 10:38

    This is a common misunderstanding which leads to confusion if you use the same Scanner for nextLine() right after you used nextInt().

    You can either fix the cursor jumping to the next Line by yourself or just use a different scanner for your Integers.

    OPTION A: use 2 different scanners

    import java.util.Scanner;
    
    class string
    {
    
        public static void main(String a[]){
        int a;
        String s;
        Scanner intscan =new Scanner(System.in);
    
    
        System.out.println("enter a no");
        a=intscan.nextInt();
        System.out.println("no is ="+a);
    
    
         Scanner textscan=new Scanner(System.in);
        System.out.println("enter a string");
        s=textscan.nextLine();
        System.out.println("string is="+s);
            }
    }
    

    OPTION B: just jump to the next Line

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

提交回复
热议问题