我在将String(birthyear)转换为int(age)时遇到麻烦。我希望有人键入他们的出生年份,并让程序进行简单的减法计算以得出他们的年龄。我是编程的新手,所以我一直在搜索,大多数地方都告诉我同样的事情。

Integer.parseInt(birthyear);


但是,这样做之后,当我尝试进行数学运算时...

int age = year-birthyear;


我得到标题中的错误。

public class WordGameScanner
{
    public static void main(String[] argus)
    {
        String name;
        String home;
        String birthyear;
        String course;
        String reason;
        String feedback;
        int year = 2013;

        Scanner input = new Scanner(System.in);
        System.out.print("What is your name: ");
        name = input.nextLine();
        System.out.print("Where are you from: ");
        home = input.nextLine();
        System.out.print("What year were you born: ");
        birthyear = input.nextLine();
        Integer.parseInt(birthyear);
        System.out.print("What are you studying: ");
        course = input.nextLine();
        System.out.print("Why are you studying " + course + ": ");
        reason = input.nextLine();
        System.out.print("How is " + course + " coming along so far: ");
        feedback = input.nextLine();

        int age = year-birthyear;

        System.out.println("There once was a person named " + name +
            " who came all the way from " + home +
            " to study for the " + course +
            " degree at --------------.\n\n" + name +
            " was born in " + birthyear + " and so will turn " + age +
            " this year.");
        System.out.println(name + " decided to study the unit ------------, because \"" +
            reason + "\". So far, ----------- is turning out to be " +
            feedback + ".");
    }
}


很抱歉,如果这是在错误的位置,这只是我在这里的第二篇文章。我只是单击“问一个问题”,然后按照指示>。<

最佳答案

int age = year-Integer.parseInt(birthyear);


调用parseInt不会将变量String birthYear重新定义为int,它只是返回一个int值,您可以将其存储在另一个变量(如int birthYearInt = Integer.parseInt(birthYear);)中或在上述表达式中使用。



您可能还需要花一点时间来考虑输入。

您的用户只能输入最后两位数字(“ 83”而不是“ 1983”),因此您可以执行以下操作:

int birthYearInt = Integer.parseInt(birthYear);
if (birthYear.length() == 2) {
  // One way to adjust 2-digit year to 1900.
  // Problem: There might not be more users born in 1900 than born in 2000.
  birthYearInt = birthYearInt + 1900;
}
int age = year = birthYearInt;


另外,您可以使用java.text.NumberFormat正确处理输入中的逗号。 NumberFormat是处理来自人类的数字的好方法,因为它处理人们格式化数字的方式不同于计算机。



另一个问题是,这使用了中国年龄编号系统,其中每个人的年龄在新年(中国农历,而不是公历)增加一个。但是,这并不是他们计算全世界年龄的方式。例如,在美国和欧洲大部分地区,您的年龄在出生周年纪念日会增加。

09-26 05:43