简体   繁体   English

如果用户输入String而不是Int,则可能出现异常

[英]Possible exception if User enters String instead of Int

I am just playing with Java.I'm trying to force my program to only accept 3 digit numbers. 我只是在玩Java,我试图强迫我的程序只接受3位数字。 I believe I have successfully done this using a while loop (please correct me if I'm wrong). 我相信我已经使用while循环成功完成了此操作(如果我输入错了,请纠正我)。 But how do I go about printing an error statement if the user enters a string. 但是,如果用户输入字符串,我该如何打印一条错误语句。 eg: "abc". 例如:“ abc”。

My code: 我的代码:

    import java.util.Scanner;
    public class DigitSum {

    public static void main(String[] args) {

    Scanner newScan = new Scanner(System.in);

        System.out.println("Enter a 3 digit number: ");
        int digit = newScan.nextInt();

        while(digit > 1000 || digit < 100)
            {           
             System.out.println("Error! Please enter a 3 digit number: ");
             digit = newScan.nextInt();
            }

        System.out.println(digit);
       }
    }

How about this? 这个怎么样?

public class Sample {
    public static void main (String[] args) {
        Scanner newScan = new Scanner (System.in);

        System.out.println ("Enter a 3 digit number: ");
        String line = newScan.nextLine ();
        int digit;
        while (true) {
            if (line.length () == 3) {
                try {
                    digit = Integer.parseInt (line);
                    break;
                }
                catch (NumberFormatException e) {
                    // do nothing.
                }
            }

            System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
            line = newScan.nextLine ();
        }

        System.out.println (digit);
    }
}

regexp version: regexp版本:

public class Sample {
    public static void main (String[] args) {
        Scanner newScan = new Scanner (System.in);

        System.out.println ("Enter a 3 digit number: ");
        String line = newScan.nextLine ();
        int digit;

        while (true) {
            if (Pattern.matches ("\\d{3}+", line)) {
                digit = Integer.parseInt (line);
                break;
            }

            System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
            line = newScan.nextLine ();
        }

        System.out.println (digit);
    }
}

将用于读取int的代码嵌入到try catch块中,每当输入错误的输入时,它将生成一个异常,然后在catch块中显示所需的任何消息

Here nextInt method itself throws an InputMismatchException if the input is wrong. 如果输入错误,则nextInt方法本身会引发InputMismatchException

try {
  digit = newScan.nextInt() 
} catch (InputMismatchException e) {
  e.printStackTrace();
  System.err.println("Entered value is not an integer");
}

This should do. 这应该做。

When you grab the input or pull the input string run through parseInt . 当您抓住输入或拉动输入字符串时,请通过parseInt运行。 This will in fact throw an exception if yourString is not an Integer : 如果yourString不是Integer这实际上将引发异常:

Integer.parseInt(yourString)

And if it throws an exception you know its not a valid input so at this point you can display an error message. 而且,如果它引发异常,您就知道它不是有效的输入,因此此时您可以显示错误消息。 Here are the docs on parseInt : 这是parseInt上的文档:

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String ) http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String

You can check if a String is of numeric value in the following ways : 您可以通过以下方式检查字符串是否为数字值:

1) Using a try/Catch Block 1)使用try / Catch块

try  
{  
  double d = Double.parseDouble(str);  
}catch(NumberFormatException nfe)  {
  System.out.println("error");
}  

2) Using regex 2)使用正则表达式

if (!str.matches("-?\\d+(\\.\\d+)?")){
  System.out.println("error");
}

3) Using NumberFormat Class 3)使用NumberFormat类

NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
if(str.length() != pos.getIndex()){
  System.out.println("error");
}

4) Using the Char.isDigit() 4)使用Char.isDigit()

for (char c : str.toCharArray())
{
    if (!Character.isDigit(c)){
      System.out.println("error");
    }
}

You can see How to check if a String is numeric in Java for more info 您可以查看如何检查Java中的字符串是否为数字以获取更多信息。

How I would do it is using an if statement. 我将如何使用if语句。 The if statement should be like this: if语句应该是这样的:

if(input.hasNextInt()){
    // code that you want executed if the input is an integer goes in here    
} else {
   System.out.println ("Error message goes here. Here you can tell them that you want them to enter an integer and not a string.");
}

Note: If you want them to enter a string rather than an integer, change the condition for the if statement to input.hasNextLine() rather than input.hasNextInt() . 注意:如果要让他们输入字符串而不是整数,请将if语句的条件更改为input.hasNextLine()而不是input.hasNextInt()

Second Note: input is what I named my Scanner. 第二点注意: input就是我命名的扫描仪。 If you name yours pancakes then you should type pancakes.hasNextInt() or pancakes.hasNextLine() . 如果您命名煎饼,则应输入pancakes.hasNextInt()pancakes.hasNextLine()

Hope I helped and good luck! 希望我有所帮助,祝你好运!

You want an Exception to occur if the user enters a string such as 'abc' instead of an integer value then the InputMismatchException is right for you. 如果用户输入诸如“ abc”之类的字符串而不是数值,则希望发生异常 ,那么InputMismatchException适合您。

Let me give a basic example for you. 让我给你一个基本的例子。

public static void main(String[] args)
    {
        Scanner ip = new Scanner(System.in);
        int a; 
        System.out.println("Enter Some Input");
        try{
            a = ip.nextInt();
        }
        catch(InputMismatchException msg){
            System.out.println("Input Mismatch Exception has occured " + msg.getMessage());
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM