在 Java 中检查输入是否为整数
问题指出,我们需要检查 Java 语言中的输入是否为整数。
使用 Java 中的 hasNextInt
方法检查输入是否为整数
System
是具有静态方法和字段的类。我们永远不能实例化它的对象。in
对象是标准输入流。该流已经打开,可以提供输入数了。
hasNextMethod
存在于 Scanner
类中,如果此扫描程序输入中的下一个标记可以被评估为 int
值,则返回 true。如果关闭了扫描程序对象,则该方法将抛出 IllegalStateException
。
package checkInputIsInt;
import java.util.Scanner;
public class CheckIntegerInput {
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner scanner= new Scanner(System.in);
if(scanner.hasNextInt()){
System.out.println("The number is an integer");
}
else{
System.out.println("The number is not an integer");
}
}
}
在第一行中,使用控制台输入从用户那里获取输入。由于输入的文本是数字,因此该数字是要打印的整数。
Enter the number: 1
The number is an integer
由于输入的文本不是数字,因此将打印 else 条件语句。
Enter the number: Hi
The number is not an integer
使用 try...catch
块检查数字是否为整数
在下面的代码块中,我们使用 Scanner 类从控制台获取用户输入。Scanner
类具有 next
方法。如果没有更多可用的令牌,则抛出 NoSuchElementException
,如果关闭此 Scanner
,则抛出 IllegalStateException
。
public class CheckIntegerInput {
public static void main(String[] args) {
System.out.print("Enter the number : ");
Scanner scanner= new Scanner(System.in);
try{
Integer.parseInt(scanner.next());
System.out.println("The number is an integer");
}catch (NumberFormatException ex) {
System.out.println("The number is not an integer ");
}
}
如果数字是整数,则上面的代码将在 try 块中显示该语句。如果该方法从其抛出 Exception
,则将执行 catch 块中存在的语句;如果无法将字符串转换为数字类型之一,则将抛出 NumberFormatException
。
上面代码的输出类似于上面给出的第一个示例代码中的输出。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。