我正在使用Java并尝试在此代码中添加一条语句,该语句在以下位置显示错误消息:
Exception in thread "main" java.util.InputMismatchException: For input string:
"31243241234123423"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at MaxInteger.main(MaxInteger.java:22)
Java提供的错误消息。我想补充一下:
System.out.println("Your Integer value is out of range.");
这是我尝试将其添加到代码中的部分代码:
import java.util.Scanner;
public class Homework1a {
public static void main(String[] args) {
int intOne = 0;
int intTwo = 0;
String operation = " ";
int result = 0;
double divResult = 0.0;
// Use the Scanner class to input data
Scanner scannerIn = new Scanner(System.in);
// Display of Program Introduction
System.out.println("This program will take your integer inputs, " +
"along with the choosen operation and calculate the results");
// Display for user to input the first integer
System.out.println("Enter the first integer:");
intOne = scannerIn.nextInt();
// Display for user to input the second integer
System.out.println("Enter the second integer:");
intTwo = scannerIn.nextInt();
// Display a list of instructions on the proper call for the operator
System.out.println("");
System.out.println("********** Operator Instructions **********");
System.out.println("\t For addition use +");
System.out.println("\t For subtraction use -");
System.out.println("\t For multiplication use *");
System.out.println("\t For division use /");
System.out.println("\t For modulus use %");
System.out.println("\t For bitwise AND use &");
System.out.println("\t For bitwise inclusive OR use |");
System.out.println("********************************************");
System.out.println("");
// Takes care of the ENTER key negating the String input below
scannerIn.nextLine();
// Display for user to input the chosen operator
System.out.println("Enter the operation:");
operation = scannerIn.nextLine();
}
}
我想要合并的另一个例子是加法,减法,乘法结果超过最大整数值时显示类似的提示。有任何建议或进一步的问题吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
有几种方法可以做到。
您可以使用 if-statement 来检查输入是否大于Integer.MAX_VALUE
。但是你需要使用容量更大的数据类型,否则当你输入的值超过Integer.MAX_VALUE
(2147483647)时,它会给你一个 InputMismatchException 。
Scanner scn = new Scanner(System.in);
Long num = 0L;
num = scn.nextLong();
if(num > Integer.MAX_VALUE)
System.out.println("Your Integer value is out of range.");
另一种方法是使用 try-catch 块。这样就不需要使用long数据类型来检入超过Integer.MAX_VALUE
的输入。
Scanner scn = new Scanner(System.in);
int num = 0;
try{
num = scn.nextInt();
}
catch(InputMismatchException e){
System.out.println("Your Integer value is out of range.");
}
我个人更喜欢第二种方法,即 try-catch 块用于 - 捕获意外行为,例如超出数据范围。此外,使用第二种方法,即使用户输入了非常大的数字(例如9999999999999999999999999999999999999),程序也会打印"Your integer value is out of range"
。第一种方法无法处理大于Long.MAX_VALUE
的输入。
Input: 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
Your Integer value is out of range.