二元运算符的坏操作数类型" - "第一种类型:int; 第二种类型:java.lang.String

0 java string int operators

我遇到了将String(birthyear)转换为int(age)的麻烦.我希望有人输入他们的出生年份,让程序做一个简单的减法计算来计算他们的年龄.我是编程的新手,所以我一直在寻找,大多数地方告诉我同样的事情.

Integer.parseInt(birthyear);
Run Code Online (Sandbox Code Playgroud)

但是,这样做,当我尝试做数学...

int age = year-birthyear;
Run Code Online (Sandbox Code Playgroud)

我在标题中收到错误.

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 + ".");
    }
}
Run Code Online (Sandbox Code Playgroud)

我很抱歉,如果这是在错误的地方,这只是我在这里的第二篇文章.我只是点击"问一个问题"并按照指示>.<

Mik*_*uel 7

int age = year-Integer.parseInt(birthyear);
Run Code Online (Sandbox Code Playgroud)

调用parseInt不会将变量重新定义String birthYearint,它只返回一个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;
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用java.text.NumberFormat正确处理输入中的逗号. NumberFormat是一种处理来自人类的数字的好方法,因为它处理人们将数字格式与计算机不同的方式.


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