2016-02-04 84 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,并且它会一直提示用户做更多的问题,就像直到用户输入空格 –