【问题标题】:What is my error in using a String in the case method在案例方法中使用字符串时我的错误是什么
【发布时间】:2015-03-28 16:59:16
【问题描述】:

我正在尝试使用Scanner 来保存变量“how”的String,如果“how” = yes 则执行。 “是”的情况,如果“否”则执行“否”的情况,这都在第一个问题的 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=input.nextLine();

标签: java string switch-statement


【解决方案1】:
 String how = null;
 switch(how.toLowerCase()) //here you are trying to convert null value 

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

赋值给

String how = input.nextLine();

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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;
      
      
       }
      
      
        }
       }}
      

      【讨论】:

        【解决方案4】:

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

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

        如果是第一次,你最好改变

        copy.equals("yes")  
        

        copy.equalsIgnoreCase("yes")

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-02
          • 1970-01-01
          • 1970-01-01
          • 2020-01-20
          • 1970-01-01
          • 2011-03-08
          • 2010-09-13
          • 1970-01-01
          相关资源
          最近更新 更多