![](/img/trans.png)
[英]bad operand types for binary %, first type java.lang.Object second type int (java)
[英]bad operand types for binary operator “-” first type: int; second type: java.lang.String
我在将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
是处理来自人类的数字的好方法,因为它处理人们与计算机格式化数字的方式不同。
另一个问题是,这使用了中国年龄编号系统,其中每个人的年龄在新年(中国农历,而不是阳历)上都增加了一个。 不过,这并不是全世界计算年龄的方式。 例如,在美国和欧洲大部分地区,您的年龄在出生周年纪念日会增加。
Integer.parseInt(birthyear);
不会覆盖生日年份值,并且不会将其类型从String更改为int
所以你要做
int intbirthyear = Integer.parseInt(birthyear);
接着
int age = year-intbirthyear;
Integer.parseInt
不会将birthyear
从String更改为int,它只是返回该字符串表示的int。 您需要将此返回值分配给另一个变量,并在减法中使用它。
即使执行了Integer.parseInt(birthyear);
如果不分配任何内容,则birthyear
将是一个字符串。
使用int age = year-Integer.parseInt(birthyear);
要么
int ibirthyear = Integer.parseInt(birthyear);
int age = year - ibirthyear;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.