如何检查用户输入是否为整数。 [英] How do I check if user input is an integer or not.

查看:80
本文介绍了如何检查用户输入是否为整数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Java问题,

从这段代码中,我试图接受用户输入并将其存储在整数变量中。然后,我试图验证变量以检查输入是否是整数。如果输入是整数,则打印输入是整数。



但是,如果用户输入不是整数类型,那么我们提示用户再次输入数字,直到用户输入一个整数。我尝试使用try和catch尝试下面的代码:

请帮助。



我尝试过:



Hi this is Java question,
From this code, I am trying to accept a user input and store it in an integer variable. Then, I am trying to validate the variable to check if the input is an integer or not. If the input is an integer, you print "The input is an integer".

However, if the user input is not of integer type, then we prompt the user to enter the number again until the user inputs an integer. I have tried the following code below using try and catch:
Please help.

What I have tried:

import java.util.*;

public class studentExpensesUOWD {
	//Used to define a new object that would contain all input functions.
	static Scanner console = new Scanner (System.in);
	
	public static void main(String[] args) {
		
		int number;
		boolean done = false;
		do
		{
			try
			{
				System.out.print("Enter a number: ");
				number = console.nextInt();
				done = true;
		}
			catch (InputMismatchException e)
			{
				System.out.println("Invalid integer input");
			}
		} while (done == false);
			
			
		System.out.println("Integer Value Accepted");
		System.exit(0);
	}

}

推荐答案

使用hasNextInt [ ^ ]扫描仪类。

示例 Java.util.Scanner.hasNextInt()方法示例 [ ^ ]
Use hasNextInt[^] of the Scanner class.
An example Java.util.Scanner.hasNextInt() Method Example[^]


您需要添加
console.next();

System.out.println("Invalid integer input");





参考 java - Scanner is使用next(),nextInt()或其他nextFoo()后跳过nextLine()? - 堆栈溢出 [ ^ ]


这篇关于如何检查用户输入是否为整数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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