numberFormatException编译错误

时间:2015-09-18 02:14:02

标签: java exception exception-handling compiler-errors

我一直在研究这个问题几个小时,我已经浏览了这个网站,看看是否有其他类似的东西,我找不到任何有用的东西。这个程序将运行并将十六进制数转换为十进制数,从我可以看出异常是有效的。但是,我在第34和35行有一个编译错误,if语句有例外(这两行是教师告诉我填写的内容,我有三次以上检查,看看是不是她写的是怎么写的我可以看到错误是用括号,但无论我如何或在何处移动它们或删除它我都无法让错误消失。这是我到目前为止所做的。

/* This program converts a hex number to a decimal number with exceptions
included.
  @author Sarah
date: 9/17/2015
 */
import java.util.Scanner;
public class NumberFormatException12_6 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);  //create scanner

    //prompt the user to enter a hex string
    System.out.println("Enter a hex number: ");
    //get hex string
    String hex = input.nextLine();

    System.out.println("The decimal value for hex number " + hex + " is: "
    + hexToDecimal(hex.toUpperCase()));
  }
  public static int hexToDecimal(String hex) {
      int decimalValue = 0;
      for(int i = 0; i < hex.length(); i++) {
          char hexChar = hex.charAt(i);
          try {
          decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
      }
          catch (Exception ex) {
                 System.out.println("Not a valid hex number");
                 System.exit(0);
              }
      }
      return decimalValue;
  }
  public static int hexCharToDecimal(char ch) throws java.lang.NumberFormatException {
      if((ch >='G' ||(ch < '0') throw new NumberFormatException("Not a valid hex number!");
      if((ch>=':'&& (ch<='@')throw new NumberFormatException("Not a valid hex number!");
      if (ch >= 'A' && ch <= 'F'){
          return 10 + ch - 'A';
      }
      else {//ch is '0', '1',...or'9'
          return ch - '0';
      }
  }
}

1 个答案:

答案 0 :(得分:1)

检查您的括号。

应该是:

  if((ch >='G') ||(ch < '0')) throw new NumberFormatException("Not a valid hex number!");
  if((ch>=':') && (ch<='@')) throw new NumberFormatException("Not a valid hex number!");