【问题标题】:Switch Incompatible Type Error开关不兼容类型错误
【发布时间】:2014-03-27 23:40:08
【问题描述】:

我正在为我的班级编写一个罗马数字程序。我正在使用 switch 语句将字符串转换为整数。但是,当我运行它时出现不兼容的类型错误。我正在运行 java 7,所以这不是问题。这是我的代码:

public static void main()
{
    // Declare local variables
    Scanner input = new Scanner(System.in);
    String rNum;
    int i;
    int[] rArray;

    // Display program purpose
    System.out.println("This Program Converts Roman numerals to decimals");
    System.out.println("The Roman numerals are I (1), V (5), X (10), L (50), C (100), D (500) and M (1000).");
    System.out.print("Enter your roman numeral: ");

    rNum = input.next().toUpperCase();

    rArray = new int[rNum.length()];

    for(i = 0; i < rNum.length(); i++){
      switch(rNum.charAt(i)){
          case "I": rArray[i] = 1;
          break;
      }
      }

【问题讨论】:

  • charAt 返回什么值类型? "I"是什么类型的?
  • Sotirios Delimolis- 有一个很好的观点,即使你有下面的答案。以后,这样想,你自己会找到大部分答案。
  • 这是一个很好的观点。我还是 java 新手,没有意识到有 char 类型。我会记住这一点。

标签: java arrays switch-statement incompatibletypeerror


【解决方案1】:

"I" 是一个单字符的字符串。 'I' 是字符 I,输入 char,这是您在 case 块中需要的。

【讨论】:

    【解决方案2】:

    您正在尝试将 char(在您的 switch () 中)与无效的 String(在您的案例块中)匹配

    【讨论】:

      【解决方案3】:

      Switch 语句包含一个字符变量,其中您的案例指的是字符串。您需要决定,您要使用字符串还是字符并始终保持一致性。

      这是解决上述问题的代码。

      class test {
          public static void main(){
              // Declare local variables
              Scanner input = new Scanner(System.in);
              String rNum;
              int i;
              int[] rArray;
      
              // Display program purpose
              System.out.println("This Program Converts Roman numerals to decimals");
              System.out.println("The Roman numerals are I (1), V (5), X (10), L (50), C (100), D (500) and M (1000).");
              System.out.print("Enter your roman numeral: ");
      
              rNum = input.next().toUpperCase();
              rArray = new int[rNum.length()];
      
              for(i = 0; i < rNum.length(); i++){
                  switch(rNum.charAt(i)){
                  case 'I': rArray[i] = 1;
                  break;
      
                  case 'V': rArray[i] = 1;
                  break;
      
                  case 'X': rArray[i] = 1;
                  break;
      
                  case 'L': rArray[i] = 1;
                  break;
      
                  //Continue in the same manner as above.
                  //Not sure, if this is the right way to convert and will
                  //convert all types of number. Just check on this.
                  }
              }
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-03-05
        • 2014-03-29
        • 2013-09-23
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多