This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?

(19个回答)


4年前关闭。




我正在尝试通过Hackerrank学习Java,目前我正在处理的挑战是将一个int,double和string并以相反的顺序将它们打印在单独的行上,但是我无法获取要打印的字符串。

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            int x=sc.nextInt();
            double y=sc.nextDouble();
            String s=sc.nextLine();

            System.out.println("String: "+s);
            System.out.println("Double: "+y);
            System.out.println("Int: "+x);
         }
    }


输入为:

42
3.1415
Welcome to Hackerrank Java tutorials!


输出为:

String:
Double: 3.1415
Int: 42


我一点都不了解Java,但是从我在网上看到的代码中,我看不出为什么这是错误的。

最佳答案

将代码的第一部分更改为此:

        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        double y = sc.nextDouble();
        sc.nextLine();  // Discard rest of current line
        String s = sc.nextLine();


java.util.Scanner将输入分为数字或行的方式有点奇怪。

10-07 19:22
查看更多