简体   繁体   English

开关不兼容类型错误

[英]Switch Incompatible Type Error

I'm writing a roman numeral program for my class. 我正在为我的课写一个罗马数字程序。 I'm using a switch statement to convert strings to integers. 我正在使用switch语句将字符串转换为整数。 However I'm getting an incompatible type error when I run it. 但是,我在运行它时遇到了不兼容的类型错误。 Im running java 7 so that's not the issue. 我正在运行Java 7,所以这不是问题。 Here's my code: 这是我的代码:

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;
      }
      }

"I" is a one character String. "I"是一个字符的字符串。 'I' is the character I, type char , which is what you need in your case block. 'I'是字符I,键入char ,这是您在case块中需要的。

您正在尝试将char (在switch ()中)与String (在您的case块中)匹配,这是无效的

The Switch statement contains a character variable, where as your case refers to string. Switch语句包含一个字符变量,您的情况是指字符串。 You need to decide, you want to use string or char and maintain the uniformity throughout. 您需要确定是否要使用字符串或char并始终保持一致性。

Here is the code that fixes the above issue. 这是解决上述问题的代码。

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.
            }
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM