【问题标题】:If user input doesn't meet conditions, return message如果用户输入不满足条件,返回消息
【发布时间】:2017-10-29 13:22:29
【问题描述】:

所以我真的是Java新手,我想做的是让用户输入一个关键字,该关键字将传递给不同的条件。如果关键字以“c”开头,它将执行cmethod。如果关键字以“n”开头,它将执行nmethod。 问题是,如果用户既不输入以“c”或“n”开头的内容,我也想显示一条消息。这是我能想到的(我知道这段代码行不通)

    public static void main(String[] args) {
    System.out.println("This program can randomize characters or numbers.");
    System.out.println("Please input \"c\" for characters, and \"n\" for numbers. ");
    Scanner choices = new Scanner(System.in);

    if (choices.next().startsWith("c")) {
        cmethod();
    }

    else {
        nmethod();
    }

    //how do I execute the code below if none of the conditions are met?
    else {
        System.out.println("Keyword is wrong.");
    }
}

编辑:尝试使用else if,但是为了执行nmethod(),用户必须输入“n”两次。

【问题讨论】:

  • else if在哪里
  • 用 else-if 替换第二个 else,检查输入的字符是否为 n ...
  • 我建议尝试将您的问题分解为多个步骤... 第 1 步:阅读单词。第2步:检查“c”。第 3 步:如果不是“c”,请检查“n”,第 4 步:Sysout。您需要将读取的值存储到变量中,因为调用choices.next() 两次会导致有趣的结果。
  • 关于您的编辑,这是因为您再次致电choices.next() 再次提示他们。将结果存储在变量中,然后您可以根据需要多次对其进行测试。
  • @Eustion 您将问题的重要部分替换为“问题已解决”,因此您的问题及其答案不再有意义。你应该保留你说你尝试了else if并且你正在阅读两个字符的部分,因为这是真正的问题(两次调用next()

标签: java if-statement next


【解决方案1】:

另一种方法:使用 switch-case

String s =choices.next();
char first = s.charAt(0);

switch(first){
  case 'c': cmethod(); break;
  case 'n':nmethod(); break;
  default : System.out.println("Keyword is wrong.");
}

【讨论】:

    【解决方案2】:

    试试:

    public static void main(String[] args) {
        System.out.println("This program can randomize characters or numbers.");
        System.out.println("Please input \"c\" for characters, and \"n\" for numbers. ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try{
        String s = br.readLine();
        if (s.startsWith("c")) {
            System.out.println("c");
            System.exit(1);
        }
        if (s.startsWith("n")){
            System.out.println("n");
            System.exit(1);
        }else {
        System.out.println("Keyword is wrong.");
        }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    

    为我工作,希望对你有用。

    【讨论】:

      【解决方案3】:

      在您可以传递方法名称的地方使用反射,如果方法存在,那么它将被找到,否则它将在您可以显示消息的地方抛出异常。

      java.lang.reflect.Method method;
      try {
           method = this.getClass().getMethod(methodName, param1.class, 
       param2.class, ..);
       } catch (SecurityException e) { ... }
      catch (NoSuchMethodException e) { ... }
      

      尝试在下面的测试示例中输入正确和错误方法名称的示例。

      public class Test {
      
      public static void main(String[] args) {
      
          Object obj = new Test();
      
          java.lang.reflect.Method method;
          try {
              method = obj.getClass().getMethod("tryone1");
              System.out.println("Found");
          } catch (SecurityException e) {
              System.out.println(" SecurityException Found");
          } catch (NoSuchMethodException e) {
              System.out.println("Not Found");
          }
      
      }
      
      public void tryone() {
          // TODO Auto-generated method stub
      
      }
      
      public void trytwo() {
          // TODO Auto-generated method stub
      
      }
      
      }
      

      请根据您的需要自定义上述示例。比如如果 c 作为参数,那么 String methodname= arg[0]+"method" 并在 getMethod("tryone1") 方法中作为方法参数名传递。

      【讨论】:

      • 想想未来你想在哪里运行任何可用的方法,如果没有找到就显示错误。
      • 我相信你没有理解他的问题。他只有两个必须选择的选项,不需要动态适应参数。 R
      【解决方案4】:

      即使您在此处提供了一些可行的解决方案,但没有人谈论真正简单的switch 声明似乎很奇怪。

      基本上:

      public static void main(String[] args) {
          System.out.println("This program can randomize characters or numbers.");
          System.out.println("Please input \"c\" for characters, and \"n\" for numbers. ");
          Scanner choices = new Scanner(System.in);
      
          switch(choices.next().charAt(0)) {
              case 'c':
                  cmethod();
                  break;
              case 'n':
                  nmethod();
                  break;
              default:
                  System.out.println("Keyword is wrong.");
          }
      }
      

      这与 next() 函数仅评估一次这一事实相结合。

      【讨论】:

      • 想知道如何使用switch 声明来做到这一点。感谢您的信息!
      【解决方案5】:

      您必须将next() 提取到一个变量中。如果您不这样做,next() 将始终返回当前关键字并继续下一个关键字。 此外,如果您想检查其他关键字,则必须使用 else if

      public static void main(String[] args) {
          System.out.println("This program can randomize characters or numbers.");
          System.out.println("Please input \"c\" for characters, and \"n\" for numbers. ");
          Scanner choices = new Scanner(System.in);
      
          String keyword = choices.next();
      
          if (keyword.startsWith("c")) {
              cmethod();
          } else if (keyword.startsWith("n")) {
              nmethod();
          } else {
              System.out.println("Keyword is wrong.");
          }
      }
      

      【讨论】:

      • 终于有人拿到了。
      • 谢谢!像魅力一样工作。
      • 很多人对else if 很生气 ^^ 准确地说,使用开关可能更合乎逻辑,因为它属于“应用不同的行为并获得没有工作时的后备案例”
      【解决方案6】:

      else 关键字正是您所需要的。您应该使用else if 来解决您的问题。为避免读取 if 之间的另一个输入,只需将 choices.next() 存储在一个变量中,然后在您的 ifs 语句中调用此变量。

      String entry = choices.next();
      if (entry.startsWith("c")) {
          cmethod();
      }
      else if (entry.startsWith("n")) {
          nmethod();
      }
      else {
          // default behaviour if wrong entry
      }
      

      只有当输入不是'c'并且是'n'时才会调用nmethod(),如果这些条件都不满足,就会进入else部分。

      【讨论】:

      • 您不能有多个 else 语句。中间行必须是else if
      • 伙计们...他不想检查 FIRST 关键字与“c”,然后检查第二个关键字与“n”...
      • 现在你的答案很完美
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2014-11-25
      相关资源
      最近更新 更多