为什么第一个字符不是大写?
Why isn't the first character uppercase?
我发现应该将第一个字符从小写字母更改为大写字母的语法。
出于某种原因,我的程序不会!当我键入 'm' 而不是 'M' 时。
我做错了什么?
public static void main(String[] args) {
System.out.print("Enter two characters: ");
Scanner input = new Scanner(System.in);
String twoChar = input.nextLine();
if(twoChar.length() > 2 || twoChar.length() <= 1){
System.out.println("You must enter exactly two characters");
System.exit(1);
}
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
if(twoChar.charAt(1) == '1'){
System.out.println("Mathematics Freshman");
}else if(twoChar.charAt(1) == '2'){
System.out.println("Mathematics Sophomore");
}else if(twoChar.charAt(1) == '3'){
System.out.println("Mathematics Junior");
}else if(twoChar.charAt(1) == '4'){
System.out.println("Mathematics Senior");
}
}
而不是
if(twoChar.charAt(0) == 'M'){
使用
if(ch == 'M'){
您正在获取大写字符,但没有使用它。
您正在将字符的大写版本分配给变量 ch
,然后您没有检查 ch
;您正在再次检查字符串中的字符。那个字符和以前一样:没有改变。
所以不用检查:
if (twoChar.charAt(0) == 'M') {
检查:
if (ch == 'M') {
没有使用局部变量
您没有使用此处大写的 char ch
,
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
您可以使用 局部变量 ch
来修复它,例如
char ch = Character.toUpperCase(twoChar.charAt(0));
if (ch == 'M') {
或通过将 toUpperCase
内联调用如
// char ch = Character.toUpperCase(twoChar.charAt(0));
if (Character.toUpperCase(twoChar.charAt(0)) == 'M') {
或使用逻辑或类似
char ch = twoChar.charAt(0);
if (ch == 'M' || ch == 'm') {
我发现应该将第一个字符从小写字母更改为大写字母的语法。
出于某种原因,我的程序不会!当我键入 'm' 而不是 'M' 时。
我做错了什么?
public static void main(String[] args) {
System.out.print("Enter two characters: ");
Scanner input = new Scanner(System.in);
String twoChar = input.nextLine();
if(twoChar.length() > 2 || twoChar.length() <= 1){
System.out.println("You must enter exactly two characters");
System.exit(1);
}
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
if(twoChar.charAt(1) == '1'){
System.out.println("Mathematics Freshman");
}else if(twoChar.charAt(1) == '2'){
System.out.println("Mathematics Sophomore");
}else if(twoChar.charAt(1) == '3'){
System.out.println("Mathematics Junior");
}else if(twoChar.charAt(1) == '4'){
System.out.println("Mathematics Senior");
}
}
而不是
if(twoChar.charAt(0) == 'M'){
使用
if(ch == 'M'){
您正在获取大写字符,但没有使用它。
您正在将字符的大写版本分配给变量 ch
,然后您没有检查 ch
;您正在再次检查字符串中的字符。那个字符和以前一样:没有改变。
所以不用检查:
if (twoChar.charAt(0) == 'M') {
检查:
if (ch == 'M') {
没有使用局部变量
您没有使用此处大写的 char ch
,
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
您可以使用 局部变量 ch
来修复它,例如
char ch = Character.toUpperCase(twoChar.charAt(0));
if (ch == 'M') {
或通过将 toUpperCase
内联调用如
// char ch = Character.toUpperCase(twoChar.charAt(0));
if (Character.toUpperCase(twoChar.charAt(0)) == 'M') {
或使用逻辑或类似
char ch = twoChar.charAt(0);
if (ch == 'M' || ch == 'm') {