2016-02-04 127 views
-1

我正在編寫一個程序,該程序假設從用戶讀取字符串並驗證字符串和操作數。只有兩個可接受的操作數是「+」和「 - 」。該字符串不能包含除數字之外的任何字符(如果有),則應該顯示爲「輸入錯誤」,但會一直提示用戶。我在下面粘貼了我的代碼,我們假設爲這個程序使用例外。我的代碼無法正常工作,它崩潰,這些數字需要進行總結,並打印出來,但我無法這樣做,與在字符串中驗證字符串異常

import java.util.Scanner; 

public class Main { 


public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 
    String term; 

    do { 
     String str = input.nextLine(); 
     term = str.trim(); 

     try { 
      System.out.println(validInput(str)); 
      System.out.println(sumNums(str)); 
     } catch (IllegalOperandException e) { 
      System.out.println("Bad Input"); 
     } catch (NumberFormatException e) { 
      System.out.println("Bad Input"); 
     } 

    } while (term.length() > 0); 

} 

public static String validInput(String string) throws IllegalOperandException { 
    String output = ""; 
    String[] stringArray = string.split("\\s+"); 
    for (String s : stringArray) { 
     for (int i = 0; i < s.length(); i++) { 
      char c = s.charAt(i); 
      if (!(Character.isDigit(c) || c == '+' || c == '-' || c == '.')) { 
       throw new IllegalOperandException(String.valueOf(c)); 
      } 
      else if(Character.isDigit(c)){ 
       Double.parseDouble(Character.toString(c)); 
      } 
     } 
     output = output + s + " "; 
    } 
    return output; 


} 

public static double sumNums (String nums) throws NumberFormatException, ArrayIndexOutOfBoundsException { 
    String[] stringArray2 = nums.split("\\s+"); 
    int i = 0; 
    int sum; 

    if (stringArray2[i].equals("-")) { 
     i++; 
     sum = Integer.parseInt(stringArray2[i]);  
    } else 
     sum = Integer.parseInt(stringArray2[i]); 

    for(int j = 0; j < stringArray2.length; j++) {  

     if (stringArray2[i].equals("+"))  
      sum+=Integer.parseInt(stringArray2[i-1]); 
     if (stringArray2[i].equals("-")) 
      sum-=Integer.parseInt(stringArray2[i+1]); 
    } 
    return sum; 


} 


} 
+0

你會得到什麼具體的錯誤? – Seb

+0

當我輸入一串字符,它假設說「不好的輸入」,它使用戶再次提示,但它給了我這個「線程中的異常」主「java.lang.Error:未解決的編譯問題: \t方法IllegalOperandException(焦炭)是不確定的型式試驗 \t在TEST.validInput(TEST.java:44) \t在TEST.main(TEST.java:21) –

回答

1

首先操作數,扔你有一個例外創造新的對象。所以,做正確的方式,以便將

throw new IllegalOperandException(c); 

其次,你傳遞一個字符一個構造函數,但構造函數只能接受String。您可以在IllegalOperandException

public IllegalOperandException(char c){ 
    this(String.valueOf(c)); //this will call IllegalOperandException(String) constructor 
} 

創建第二個構造或者你拋出一個例外

throw new IllegalOperandException(String.valueOf(c)); 

第三你可以改變路線,return false不可達。如果拋出異常,代碼執行直接跳轉到catch語句,並且您的validInput(String)無法返回任何內容(無處可返回值)。所以,你不需要它

+0

OMG現在的工作,但現在當我嘗試這個測試像這樣的情況下,「3231 + sdsa」它假設只是說「壞的輸入」,但輸出是「3231 +壞的輸入」,我在哪裏添加while循環,以便在用戶獲得用戶可以輸入的「錯誤輸入」消息不同的值,程序假設在用戶輸入空字符串時終止 –

+0

[Here](https:// g ist.github.com/6de47c5d4929d2efce14)是略有修改的版本。雖然我只會使用正則表達式,然後所有的檢查可以縮小到3-4行 – Meegoo

+0

你會如何總結像232 + 10這樣的整數將會是242,並且它會一直提示用戶做更多的問題,就像直到用戶輸入空格 –