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

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

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

问题

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

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

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.

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

答案1

得分: 0

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

  1. Scanner sc = new Scanner(System.in);
  2. System.out.println("请输入一个数字:");
  3. while (!sc.hasNextInt()) {
  4. System.out.printf("你输入的是“%s”。请再次输入一个数字:%n", sc.next());
  5. }
  6. int num = sc.nextInt();
  7. System.out.println(num);
  8. sc.close();
英文:

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

  1. Scanner sc = new Scanner(System.in);
  2. System.out.println("Please enter a number:");
  3. while (!sc.hasNextInt()) {
  4. System.out.printf("Your input was \"%s\". Please enter a number:%n", sc.next());
  5. }
  6. int num = sc.nextInt();
  7. System.out.println(num);
  8. 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:

确定