如何在Java中确保扫描器接收到的数字是整数?

huangapple go评论71阅读模式
英文:

How can I check, the number that scanner received is an integer certainly in java?

问题

我有一个必须接受整数作为输入的方法。我如何可以确定它肯定是一个整数。如果输入是一个字符串,那么再次获取数字。

public int getMobileNumber() {
    System.out.println("输入手机号码:");
    int mobileNumber = input.nextInt();
    System.out.println("手机号码已注册!");
    return mobileNumber;
}
英文:

I have a method that must get an integer as input. How can I check that it is a integer certainly. if input is a string so get number again.

public int getMobileNumber() {
    System.out.println("Enter Mobile Number: ");
    int mobileNumber = input.nextLong();
    System.out.println("Mobile Number Registered!");
    return mobileNumber;
}

答案1

得分: 0

你可以使用hasNextInt方法和一个while循环来确保获得一个整数:

Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数字:");

while (!sc.hasNextInt()) {
    System.out.printf("你输入的是“%s”。请再次输入一个数字:%n", sc.next());
}

int num = sc.nextInt();
System.out.println(num);

sc.close();
英文:

You can use the hasNextInt method and a while loop to get definitely an integer:

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number:");

while (!sc.hasNextInt()) {
    System.out.printf("Your input was \"%s\". Please enter a number:%n", sc.next());
}

int num = sc.nextInt();
System.out.println(num);

sc.close();

huangapple
  • 本文由 发表于 2020年9月21日 04:08:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63983210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定