【问题标题】:After getting user input "Scanner name = new Scanner(System.in);" how to use is in a if statement? [duplicate]获得用户输入“扫描仪名称=新扫描仪(系统.in);”后如何在 if 语句中使用 is? [复制]
【发布时间】:2014-11-13 10:32:51
【问题描述】:

所以我在学习java,一点一点地获得更多的知识,现在我正在关注tutroials和其他网站上的学习,但我陷入了一个我无法弄清楚问题所在的问题。

import java.util.Scanner;

class apples{
    public static void main(String args[]){

        System.out.print("Player Name?");
        Scanner name = new Scanner(System.in);
        System.out.print(name.nextLine());

        System.out.print(" ,how old are you?");
        Scanner age = new Scanner(System.in);
        System.out.print(age.nextLine());



        if (age >= 15){
            System.out.println("welcome to Azura World");
        }else{
            System.out.println("insufficient experience");
        }
    }
}

从这应该做的是,询问玩家姓名,我键入它应该询问姓名,你几岁?有了这个,我有了输入的年龄,因为我想在 if 语句中使用它,但它不起作用,我不明白为什么。所以如果有时间请解释一下。

我现在也使用THIS 作为指南

【问题讨论】:

    标签: java if-statement java.util.scanner system.in


    【解决方案1】:

    这是因为 java 是静态类型的,ScannerreadLine 方法返回一个字符串,String 不是 intInteger,因此无法与 @987654326 进行比较@ 或 Integer。您需要将返回的值“转换”为Integer,以便能够使用 Paras Mittal 或此类解决方案将其与 int 进行比较(我个人会选择 Paras 解决方案,因为它使用本机 Scanner 功能)。

    这增加了一些困难,因为您现在必须处理用户没有为您提供“Integer-like”答案的情况(就像您最终必须使用实际代码一样,它只是没有'暂时不出现)。在这种情况下,readLine 将抛出一个InputMismatchException,您至少有两种方法可以处理(可能还有更多,取决于您的想象):

    1. 因为它继承了 RuntimeException,所以您可以忽略它,让它对您的用户或您方法的使用者造成影响
    2. 您可以在age.nextInt(); 周围加上try...catch 子句,然后执行对您的用例有意义的任何事情(忽略它并为该值设置巧妙的默认值,再次询问用户),您也可以先发制人地测试该用户输入可以转换为整数或继续询问。

    【讨论】:

      【解决方案2】:
      public static void main(String[] args) {
          System.out.print("Player Name?");
          Scanner name = new Scanner(System.in);
          System.out.print(name.nextLine());
      
          System.out.print(" ,how old are you?");
          Scanner age = new Scanner(System.in);
      
          int ageVal = age.nextInt();
      
          System.out.print(ageVal);
      
          if (ageVal >= 15){
              System.out.println("welcome to Azura World");
          }else{
              System.out.println("insufficient experience");
          }
      }
      

      【讨论】:

        【解决方案3】:

        我认为您只是在打印值,首先将其存储在某个变量中,然后进行比较:

        String userage = age.nextLine();
        int a=Integer.valueOf(userage);
         if (a >= 15){
                System.out.println("welcome to Azura World");
            }else{
                System.out.println("insufficient experience");
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-20
          • 1970-01-01
          • 2015-10-02
          • 2016-06-12
          • 1970-01-01
          • 1970-01-01
          • 2022-01-07
          相关资源
          最近更新 更多