如何使两个输入在同一循环下工作?

时间:2019-07-27 15:24:34

标签: java

我正在尝试解决一个基本问题,即寻找具有5年以上经验的人员。但是代码不是那样运行的。

这用于在同一for循环中运行两个用户输入命令:

Scanner s = new Scanner(System.in);
int n = s.nextInt();

for (int i = 0; i <= n; i++) {
    String name = s.nextLine();
    System.out.println("enter experience");
    int e = s.nextInt();

    if (e > 5) {

    } else {

    }
}

预期结果是拥有5年以上经验的人数,但实际是代码仅要求输入经验。

4 个答案:

答案 0 :(得分:1)

使用nextInt()时,您立即按Enter键吗? 实际发生的是nextInt()接受了整数输入,然后按Enter,现在新行已被String name = s.nextLine()占用;然后代码立即转到您的System.out.println("enter experience");

您应该做的就是在

之类的循环中简单地添加另一个s.nextLine()。
Scanner s = new Scanner(System.in);
                int n = s.nextInt();
                String name = s.nextLine();

                for (int i = 0; i <= n; i++) {
                        s.nextLine(); // put this here 
                        System.out.println("enter name");

这样,新语句将占用新的行键,现在您可以输入name。

答案 1 :(得分:0)

尝试以下代码:

Scanner s = new Scanner(System.in);
int n = Integer.parseInt(s.nextLine());

for (int i = 0; i <= n; i++) {
    String name = s.nextLine();
    System.out.println("enter experience");
    int e = Integer.parseInt(s.nextLine());

    if (e > 5) {

    } else {

    }
}

答案 2 :(得分:0)

您需要以某种方式清洁缓冲区。 这可能对您有帮助。

以下将解决该问题:

Scanner s = new Scanner(System.in);

int n = s.nextInt(); // the input       
s.next();            // clean the buffe

答案 3 :(得分:0)

我想做的是比较用户注册后的年限。如果是这种情况,那么您需要将用户及其统计信息存储在HashMap之类的某个位置,然后过滤该HashMap。