本文介绍了如何以更具体的方式处理NumberFormatException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以更特定的方式处理NumberFormatException。
输入以下内容时,尝试分配除整数以外的任何内容时,会发生此异常:
I want to handle NumberFormatException in more specific way.This exception occurs, when it tries assign anything but an integer, when the following is entered:
- string
- 字符
- 空输入
- 双数
- string
- character
- empty input
- double number
根据输入的内容,我想显示一条正确的消息,例如
Depending on what was entered I want to display a proper message, like
或
下面的代码捕获 NumberFormatException
一般。
我想知道是否有办法包含更多catch子句。
I wonder is there a way to include more catch clauses.
import java.util.Scanner;
public class TestException {
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
try {
input = Integer.parseInt(scan.next());
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
System.out.println("You've entered non-integer number");
System.out.println("This caused " + e);
}
}
}
推荐答案
首先从用户那里获取输入,然后尝试将其转换为整数。
First take the input from the user and after that try to convert it to integer.
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
String inputString = scan.next();
try {
input = Integer.parseInt();
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
if(inputString.equals("") || inputString == null) {
System.out.println("empty input");
} else if(inputString.length == 1) {
System.out.println("char input");
} else {
System.out.println("string input");
}
}
}
这篇关于如何以更具体的方式处理NumberFormatException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!