简体   繁体   English

扫描仪停止读取输入

[英]Scanner stops to read input

import java.util.Scanner;
public class test {

public static void main(String[] args) 
{
    Scanner input = new Scanner (System.in);
    boolean US1 = false;
    boolean game;
    int score = 1;
    int wage = 0;   
    int fin_score = 0;
    String ans;

    if (US1 == false)
    {
        game = false;
        System.out.println (score);
        System.out.println("Enter a wager");
        wage =  input.nextInt();
    }

    if (wage < score)
    {
        System.out.println ("What is the capital of Liberia?");
        ans = input.nextLine();

        if (ans.equalsIgnoreCase("Monrovia"))
        {
            System.out.println ("You got it right!");
            System.out.println ("Final score " + fin_score);
        }
    }
    // TODO Auto-generated method stub
}
}

For some reason once I enter a value for wage, the code prints "What is the capital of Liberia?" 由于某种原因,一旦输入工资值,代码就会显示“利比里亚的首都是多少?” then terminates. 然后终止。 Im not sure what is going on, why the scanner will not let me input the answer for the question 我不确定发生了什么,为什么扫描仪不会让我输入问题的答案

The problem is that Scanner nextInt doesn't consume the Enter 问题是Scanner nextInt不消耗Enter

So you must use a nextLine() for it 所以你必须使用nextLine()

Add the following: 添加以下内容:

input.nextLine();

right after 之后

wage = input.nextInt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM