如何处理错误数据类型输入的异常但该变量不是Java中的对象

时间:2016-12-11 19:14:56

标签: java

我曾尝试这样做4个小时,但我仍然可以得到它。 我该如何处理这个输入? 我尝试使用instanceof但不是对象。 当我输入非int内容时,它认为我输入零。

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);
    }
}

2 个答案:

答案 0 :(得分:0)

Integer.parseInt会抛出NumberFormatException。抓住它,这是"Integer please!"的情况。

答案 1 :(得分:-1)

在调用Integer.parseInt()之前,你能不能检查输入字符串是否在你想要的整数范围内?

if (char >= '1' && char <= '5') {
    num = Integer.parseInt(char);
}