1

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

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 语句中使用它,但它不起作用,我不明白为什么。所以如果有时间请解释一下。

我现在也使用这个作为指南

4

3 回答 3

0

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

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");
    }
于 2014-11-13T10:39:23.297 回答
0
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");
    }
}
于 2014-11-13T10:39:39.583 回答
0

这是因为 java 是静态类型的,并且Scanner'sreadLine方法返回一个 String,AString不是 anint或 an Integer,因此不能与 anint或 an进行比较Integer。您需要使用 Paras Mittal 或 suchit 解决方案将返回的值“转换”为 anInteger以便能够将其与 int 进行比较(我个人会选择 Paras 解决方案,因为它使用本机Scanner功能)。

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

  1. 因为它继承RuntimeException,你可以忽略它,让它吹向你的用户,或者你的方法的消费者
  2. age.nextInt();你可以用一个子句包围,try...catch然后做任何对你的用例重要的事情(忽略它并为该值设置聪明的默认值,再次询问用户),你也可以先发制人地测试用户输入是否可以转换为整数或保留问。
于 2014-11-13T11:08:04.970 回答