如何处理错误数据类型输入但变量不是Java中的对象的异常
我已经试了4个小时了,但我还是能做到。 我如何处理这个输入? 我试图使用如何处理错误数据类型输入但变量不是Java中的对象的异常,java,Java,我已经试了4个小时了,但我还是能做到。 我如何处理这个输入? 我试图使用instanceof,但它不是一个对象。 当我输入非整数的东西时,它认为我输入的是零 if (input was not int or other datatype or even null ){ System.out.println("Integer please!"); } 完整代码: import java.util.*; public class InputParsing{ static int
instanceof
,但它不是一个对象。
当我输入非整数的东西时,它认为我输入的是零
if (input was not int or other datatype or even null ){
System.out.println("Integer please!");
}
完整代码:
import java.util.*;
public class InputParsing{
static int [] a = {80, 60, 72, 85, 90};
static String input;
static String output;
static Scanner sc = new Scanner(System.in);
public static void parseInput(){
int num = 0;
double total = 0;
double average = 0;
output = "The 5 marks are:";
for (int i=0; i<5; i++){
output += " "+a[i];
}
output += "\nAverage of how many numbers? ";
System.out.print(output);
input = sc.nextLine();
try{
System.out.println("Input length = " + input.length());
num = Integer.parseInt(input);
if(num <= 0){
throw new ArithmeticException();
}
total = 0;
for (int i=0; i<num; i++)
total += a[i];
average = total / num;
}
catch(Exception e){
if (input was not int){
System.out.println("Integer please!");
}
else if(num > 0){
System.out.println("Not more than 5 please!");
}
else if(num < 0){
System.out.println("No negative number please!");
}
else if(num == 0){
System.out.println("Don't input zero!");
}
else{
System.out.println("Something wrong!");
}
throw new ArithmeticException();
}
finally{
System.out.println("Number = " + num);
}
System.out.println("Average over first " + num +
" numbers = " + average);
}
public static void main(String[] args){
boolean done = false;
do{
try{
parseInput();
done = true;
}catch(Exception e){
System.out.println("Number should be 1 to 5!");
}finally{
System.out.println();
}
}while (! done);
}
}
import java.util.*;
公共类输入解析{
静态int[]a={80,60,72,85,90};
静态字符串输入;
静态字符串输出;
静态扫描仪sc=新扫描仪(System.in);
公共静态void parseInput(){
int num=0;
双倍合计=0;
双平均=0;
output=“这5个标记是:”;
对于(int i=0;iInteger.parseInt
将抛出一个NumberFormatException
。捕获它,这是您对“Integer please!”的情况。
在调用Integer.parseInt()之前,是否可以检查输入字符串是否在您想要的整数范围内
i、 e
if(char>='1'&&char-cause是学校的一个实验室,所以有些代码我不知道为什么会这样。因为有些代码是给定的。变量input
的类型是String
(否则对Integer.parseInt(input)
的解析调用就没有多大意义了)。这样的变量无法与整数值进行比较。我的代码出错,我的意思是将字符与整数的alpha表示进行比较
if (char >= '1' && char <= '5') {
num = Integer.parseInt(char);
}