使用扫描仪扫描Java中的输入

此代码检查用户输入的内容是否有效.如果不是数字,它将继续循环直到收到数字.之后,它将检查该数字是否在界限内或小于界限.它将继续循环直到收到入站号码.但是我的问题是,当我打印选择项时,它仅显示插入的最后一个数字之后的前一个数字.为什么会这样呢?

 

 

public void askForDifficulty(){
    System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");
    int choice = 0;
    boolean notValid = true;
    boolean notInbound = true;
    do{
        while(!input.hasNextInt()){
            System.out.println("Numbers Only!");
            System.out.print("Try again: ");
            input.nextLine();
        }
            notValid = false;
            choice = input.nextInt();
    }while(notValid);

    do{
        while(input.nextInt() > diff.length){
            System.out.println("Out of bounds");
            input.nextLine();
        }
        choice = input.nextInt();
        notInbound = false;
    }while(notInbound);

    System.out.println(choice);
}

最佳答案

这是因为while条件中的input.nextInt()使用了整数,因此它后面的那个读取了下一个.编辑您还需要组合两个循环,如下所示:

 

 

int choice = 0;
for (;;) {
    while(!input.hasNextInt()) {
        System.out.println("Numbers Only!");
        System.out.print("Try again: ");
        input.nextLine();
    }
    choice = input.nextInt();
    if (choice <= diff.length) break;
    System.out.println("Out of bounds");
}
System.out.println(choice);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值