2016-12-11 21 views
0

我曾試過這樣做了4個小時,但我仍然可以得到它。 我如何處理這個輸入? 我試過使用instanceof但不是一個對象。 當我輸入非int的東西,它認爲我輸入零。如何處理錯誤的數據類型輸入的異常,但該變量不是Java中的對象

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

回答

0

Integer.parseInt將拋出一個NumberFormatException。抓住它,這是你的情況"Integer please!"

-1

你能不能在你調用Integer.parseInt()之前檢查輸入字符串是否在你想要的整數範圍內?

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

,因爲是從學校實驗室,使一些代碼,我不知道它爲什麼要這樣。因爲給出了一些代碼。 –

+0

變量'input'的類型是'String'(否則對'Integer.parseInt(input)'的解析調用沒有多大意義)。這種變量不能與整數值進行比較。 – Seelenvirtuose

+0

我的代碼發生了錯誤,我的意思是比較一個字符與整數的字母表示 –

相關問題