public class Main { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
String s = sc.nextLine();
System.out.print("a: " + a + " b: " + b + " s: " + s); }
}
为什么上述代码输入:
1
2
String
的时候输出只输出a: 1 b: 2 s: 
(当输入2的时候就已经输出了,我还没输入String呢)难道想要输出a: 1 b: 2 s: String只能用下述的的代码么?
public class Main { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();
System.out.print("a: " + a + " b: " + b + " s: " + s); }
}

解决方案 »

  1.   

    此扫描器执行当前行,并返回跳过的输入信息。 此方法返回当前行的其余部分,不包括结尾处的行分隔符。当前位置移至下一行的行首。 看看说明,
    你再输入
    1
    2  3知道是为什么了!
    他就是读你的第2此nextInt()之后的剩余的部分!
      

  2.   

    public class Main {    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            String s = sc.nextLine();
            System.out.print("a: " + a + " b: " + b + " s: " + s);    }
    }以下是我的理解是,哪里不对还请大家指正:String s = sc.nextLine();
    这里读到的是一个空字符串。因为你在输入完第二个数字以后,按了一下回车。
    假设你第二个数字输入的是:5(加一个回车)
    则程序实际收到的是:5\r\n
    nextInt() 扫描到了5nextLine();继续扫描,这个方法会返回当前行的剩余部分,(一直到遇到行分隔符为止,而且不包括行分隔符)
    因为5的后面是一个行分隔符\r ,所以nextLine() 就只扫到了一个空的字符串。public class Main {    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = Integer.parseInt(sc.nextLine());
            int b = Integer.parseInt(sc.nextLine());
            String s = sc.nextLine();
            System.out.print("a: " + a + " b: " + b + " s: " + s);    }
    }
    这个代码可以运行成功,是因为sc.nextLine() 会将读取到的行分隔符自动去掉。
    所以你在输入第二个数字的时候:5(加一个回车)
    输入的是5\r\n
    不过程序实际扫描到的是5当再执行这句代码的时候:String s = sc.nextLine();因为行里面已经没有数据了,所以程序会阻塞,一直到你再输入数据为止。
      

  3.   

    public class Main {    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            String s = sc.nextLine();
            System.out.print("a: " + a + " b: " + b + " s: " + s);    }
    }
    此代码我运行了一下,没有发现楼主所说的问题啊
      

  4.   

    不会吧?
    你运行的时候可以输出String?
      

  5.   

    毫无问题,不知道楼主在什么环境下运行的
    我是在eclipse下
      

  6.   

    1(回车)
    2(回车)
    这时候就输出了
    我没机会输入String
      

  7.   

    怎么会呢?楼主JDK哪个版本的?我的是5.0
      

  8.   


    public class Main {    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = Integer.parseInt(sc.nextLine());
            int b = Integer.parseInt(sc.nextLine());
            sc.nextLine();//加上这句试试
            String s = sc.nextLine();
            System.out.print("a: " + a + " b: " + b + " s: " + s);    }
    }
      

  9.   

    public String nextLine()此扫描器执行当前行,并返回跳过的输入信息。
    此方法返回当前行的其余部分,不包括结尾处的行分隔符。
    当前位置移至下一行的行首。