有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java将char从方法传递回main

我正在写一个方法,检查三个字母中有一个已经输入。 问题是我无法获取返回字符的方法

中的char变量最初读入Scanner并输入数组

这里是阅读的地方

            //get house Type and send into array
            System.out.println("Property " +numProperty+ " : Terraced, Semi-Detached, Detached: (T/S/D)");
            houseType [i] = readLetter(input.next().charAt(0));
            input.next().charAt(0);

这就是readLetter的方法

    public static char readLetter(char input){


        if(input != 'T'||input != 't'||input != 'S'||input != 's'||input != 'D'||input != 'd')
            System.out.println("Invalid input! Enter option T, S or D? ");

        else    

        return input;       

    }

错误是

The method must return a result of type char.


共 (4) 个答案

  1. # 1 楼答案

    readLetter方法中,两种情况下都必须返回值,例如:

    public static char readLetter(char input) {
      if(input != 'T' && input != 't' && input != 'S' && input != 's' && input != 'D' && input != 'd') {
        System.out.println("Invalid input! Enter option T, S or D? ");
        return 0;  
      } else {
        return input;
      }
    }
    

    如果input != 'T' && input != 't' && input != 'S' && input != 's' && input != 'D' && input != 'd',则返回0。您需要在主方法中处理此问题,如下所示:

    System.out.println("Property " +numProperty+ " : Terraced, Semi-Detached, Detached: (T/S/D)");
    char ch = readLetter(input.next().charAt(0));
    if ( ch != 0 ) {
      // the input was valid
      houseType[i] = readLetter(input.next().charAt(0));
    }
    input.next().charAt(0);
    

    更新:有人注意到,您的条件input != 'T'||input != 't'||input != 'S'||input != 's'||input != 'D'||input != 'd'将始终返回true(即,您的输入将始终是非法的),但修复方法是将||替换为&&(将OR更改为AND)

    我编辑了代码以反映这一点

  2. # 2 楼答案

    试试这个:

    public static char readLetter(char input){
    
    
        if(input != 'T'&& input != 't'&& input != 'S'&&input != 's'&&input != 'D'&&input != 'd')
        {    
            System.out.println("Invalid input! Enter option T, S or D? ");
            return 0; //or something that signals invalid input
        }
        else    
        {
           return input;
        }       
    
    }
    
  3. # 3 楼答案

    您正在这样做:

    if(input != 'T'||input != 't'||input != 'S'||input != 's'||input != 'D'||input != 'd')
         System.out.println("Invalid input! Enter option T, S or D? ");
    else    
        return input; 
    

    因此,由于您没有使用{},因此只有在不满足条件时,代码才会返回

    所以编译器会抱怨,因为该方法并不总是返回字符

  4. # 4 楼答案

    当用户输入无效值时,您将丢失案例

    在这种情况下,该方法应该返回什么

    在IMO中,此方法应返回true或false,指示传递的输入是否有效(T、S或D)