hasNextInt()在Java中的用法 [英] Usage of hasNextInt() in java

查看:69
本文介绍了hasNextInt()在Java中的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学者,对使用hasNextInt()感到困惑.如果它检查了输入,那么我们不应该之后使用它吗?但是,在下面的给定代码中,它与if语句一起使用.请指教.

I am a beginner and I am confused with using hasNextInt(). If it checks the input, then shouldn't we be using it after asking the user for input? However, in the given code below, it is used with if statement. Please advise.

import java.util.Scanner;
public  class Test {
    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);

        System.out.println("Enter your number");
        if (userInput.hasNextInt()) {
            int numberEntered = userInput.nextInt();
            System.out.println("You entered an integer");
        } else {
            System.out.println("you didn't enter an integer");
        }
    }
}

推荐答案

您可以使用它来测试用户的输入,因此可以确保在调用nextInt时不会出现异常,因为输入不是int,这也不会使他的光标向前移动:

You use it to test the user's input, so you are sure that when you call nextInt you won't have an exception because the input wasn't an int, it's also not moving he cursor forward:

Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt()){
    System.out.println(scanner.nextInt());
}

这篇关于hasNextInt()在Java中的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆