我在将 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
不会将变量StringbirthYear
重新定义为int
,它只是返回一个int
您可以将其存储在另一个变量中的值(例如 intbirthYearInt = 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
是处理人类数字的好方法,因为它处理人类数字格式的方式与计算机不同。
另一个问题是,它使用中国的年龄计数系统,每个人的年龄在新年(中国农历,而不是公历)都会加一。但这并不是世界范围内计算年龄的方式。例如,在美国和欧洲大部分地区,您的年龄会在生日周年纪念日增加。
关于java - 二元运算符 "-"第一个类型 : int; second type: java. lang.String 的错误操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212925/