我在 case 方法中使用 String 的错误是什么

What is my error in using a String in the case method

我正在尝试使用 Scanner 为变量 "how" 保存一个 String,如果 "how" = yes 则执行。 'yes' 案例和 if 'no' 执行 'no' 案例这都在第一个问题

的 else 语句中
package test;
import java.util.Scanner;

public class Try {
    public static void main(String[] args) {
        System.out.println("hello world");
        Scanner input = new Scanner(System.in);
        System.out.println("Do you wanna make android apps");
        System.out.println("Yes or no ?");
        String copy=input.nextLine();
        System.out.println(copy);

        if(copy.equals("yes")) {
            System.out.println("you should continue java");
        } else {
            System.out.println("Do you wanna make iso apps");
            System.out.println("yes or no");
            String how = null;
            switch(how.toLowerCase()){
                case "yes" :
                    System.out.println("test worked");
                    break;
                case "no":
                    System.out.println("test worked 2");
                    break;
            }
        }
    }
}

String how = null;更改为String how = input.nextLine();

package test;
import java.util.Scanner;
public class Try {
private enum how_string { yes,no};
public static void main(String[] args) {
System.out.println("hello world");
 Scanner input = new Scanner(System.in);
 System.out.println("Do you wanna make android apps");
 System.out.println("Yes or no ?");
 String copy=input.nextLine();
 System.out.println(copy);
 if(copy.equals("yes")){
     System.out.println("you should continue java");





 }else{

 System.out.println("Do you wanna make iso apps");
 System.out.println("yes or no");
 String how=input.nextLine();
 how_string p = how_string.valueOf(how.toLowerCase());
 switch(p){

 case yes :System.out.println("test worked");
 break;
 case no :System.out.println("test worked 2");
 break;


 }


  }
 }}

就像你的String copy=input.nextLine();

您需要将 String how = null; 更改为 String how = input.nextLine();

对于您的第一个 if else,您最好更改

copy.equals("yes")  

copy.equalsIgnoreCase("yes")

 String how = null;
 switch(how.toLowerCase()) //here you are trying to convert null value 

以上语句试图将 null 值转换为小写。

赋值给

String how = input.nextLine();

希望这能解决您的问题..