Java将char从方法传递回main

时间:2016-03-19 21:19:47

标签: java

我正在编写一种检查已输入3个字母中的1个字母的方法。 问题是我无法获得返回char的方法。

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;       

    }

错误是

  

该方法必须返回char类型的结果。

4 个答案:

答案 0 :(得分:1)

试试这个:

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

}

答案 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。你需要在main方法中处理它,如下所示:

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(即您的输入始终是非法的)但修复方法是将||替换为{{ 1}}(将OR更改为AND)。

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

答案 2 :(得分:0)

当用户输入无效值时,您会错过这种情况。

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

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

答案 3 :(得分:0)

你这样做:

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; 

因为您没有使用 {} ,所以只有在不符合条件的情况下才会返回代码。

因此您的编译器会抱怨,因为该方法并不总是返回char ...