英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论