在 Java 中检查输入是否为整数

原文:https://www.studytonight.com/java-examples/check-if-input-is-integer-in-java

在本教程中,我们将学习如何确定给定的输入是否是整数。如果整个输入只包含数字,即0-9 ,那么它将被认为是一个整数。为了实现检查有效整数的程序,我们将使用三种方法:

  • 使用Integer.parseInt()方法检查有效整数
  • 使用Scanner.hasNextInt()方法检查有效整数
  • 使用Character.isDigit()方法检查有效整数

1)使用 Integer.parseInt()检查有效整数的示例

在本例中,我们将尝试将一个字符串解析为整数,如果该字符串只包含数字,那么它不会抛出异常,我们可以打印输出,表明给定的输入是有效的整数。如果给定的输入不是有效的整数,那么它会抛出一个异常,这时我们可以通过给出一个消息来处理一个异常,即当前的输入不是有效的整数。

public class StudyTonight 
{ 
    public static void main(String[] args)   
    { 
        String input = "1234";           
        try 
        { 
            Integer.parseInt(input); 
            System.out.println(input + " is a valid integer"); 
        }  
        catch (NumberFormatException e)  
        { 
            System.out.println(input + " is not a valid integer"); 
        } 
    } 
}

1234 是有效整数

另一方面,如果我们提供整数以外的输入,它将给出输出,因为给定的字符串不是有效的整数。

public class StudyTonight 
{ 
    public static void main(String[] args)   
    { 
        String input = "ab1234c";           
        try 
        { 
            Integer.parseInt(input); 
            System.out.println(input + " is a valid integer"); 
        }  
        catch (NumberFormatException e)  
        { 
            System.out.println(input + " is not a valid integer"); 
        } 
    } 
}

ab1234c 不是有效的整数

2)使用 Scanner.hasNextInt()方法检查有效整数的示例

Scanner.hasNextInt()方法检查当前输入是否包含整数。如果输入中出现整数,此方法将返回 true,否则将返回 false。

import java.util.Scanner;
public class StudyTonight 
{ 
    public static void main(String[] args)   
    { 
        Scanner sc = new Scanner(System.in);   
        if(sc.hasNextInt()) {
           System.out.println(sc.nextInt()+" is valid Integer");
        }
        else
        {
             System.out.println(sc.nextInt()+" is valid Integer");
        }
        sc.close();
    } 
}

123 123 为有效整数

3)使用 Character.isDigit()方法检查有效整数的示例

Character.isDigit()是检查当前字符是数字(数字)还是任何其他字符的方法。这个代码背后的逻辑是,给我们一个字符串,我们将检查每个字符和任何不是数字的字符,然后我们设置一个标志为假,标志必须设置为真。遍历字符串后,我们检查标志的状态,如果它为真,那么我们将打印当前输入的有效整数。

public class StudyTonight 
{ 
    public static void main(String[] args)   
    { 
        String input = "1234";           
        Boolean flag=true;
        for(int a=0;a<input.length();a++)
        {
            if(a==0 && input.charAt(a) == '-')
                continue;
            if( !Character.isDigit(input.charAt(a)))
                flag=false;                 
        }
        if(flag)
        {
            System.out.println(input+" is valid Integer");
        }
    } 
}

1234 是有效整数

结论:

在本文中,我们学习了检查给定的输入是否是有效的整数。首先我们可以使用Integer.parseInt()方法、Scanner.hasNextInt()方法和Character.isDigit()方法所有的方法都同样有效。Scanner.hasNextInt()只能在我们使用Scanner 类接受输入的情况下使用。