java - numberFormatException 编译错误

标签 java exception compiler-errors

我已经为此工作了几个小时,我浏览了整个网站,看看其他人是否有类似的东西,但我找不到任何有帮助的东西。该程序将运行并将十六进制数转换为十进制数,据我所知,异常正在运行。然而,我在第 34 行和第 35 行有一个编译错误,即带有异常(exception)的 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';
      }
  }
}

最佳答案

检查你的括号。

应该是:

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

关于java - numberFormatException 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32642795/

相关文章:

c# - 什么是后置条件异常?

造成循环继承的java观察者

java - 创建初始重复数据的二维字符串数组的最有效方法是什么?

java - 如何在java上整齐地提取子路径以考虑根文件夹和无根文件夹

Java Applet 错误,NullPointerException

Java,App Insights : "I/O Exception: Invalid Argument or cannot assign requested address" only when I run using docker. gradle 在本地没有错误

java - 使用 ExceptionMapper 记录 CLIENT_ERROR

c# - If 语句评估为 false 但仍然分支,就好像它是 true

c# - msdn C# 图形示例中的无效参数错误

c++ - 抛出有关头文件 C++ 中的类型的错误