How can I subtract the birth year and current year to display age?
如何减去出生年份和当前年份以显示年龄?
Scanner user_input = new Scanner(System.in);
String birth_year;
System.out.print("Enter your the year you were born: ");
birth_year = user_input.next();
int age, current_year = 2016;
age = current_year - birth_year;
System.out.println("Your age is "+age);
2 个解决方案
#1
2
Use user_input.nextInt()
to read integer values, you can't substract String and int:
使用user_input.nextInt()读取整数值,不能减去String和int:
Scanner user_input = new Scanner(System.in);
int birth_year;
System.out.print("Enter your the year you were born: ");
birth_year = user_input.nextInt();
int age, current_year = 2016;
age = current_year - birth_year;
System.out.println("Your age is "+age)
#2
0
You can use something like this also
你也可以使用这样的东西
LocalDate birthdate = LocalDate.of(YEAR, MONTH, DAY);
LocalDate now = LocalDate.now();
int age = Period.between(birthdate, now).getYears();
#1
2
Use user_input.nextInt()
to read integer values, you can't substract String and int:
使用user_input.nextInt()读取整数值,不能减去String和int:
Scanner user_input = new Scanner(System.in);
int birth_year;
System.out.print("Enter your the year you were born: ");
birth_year = user_input.nextInt();
int age, current_year = 2016;
age = current_year - birth_year;
System.out.println("Your age is "+age)
#2
0
You can use something like this also
你也可以使用这样的东西
LocalDate birthdate = LocalDate.of(YEAR, MONTH, DAY);
LocalDate now = LocalDate.now();
int age = Period.between(birthdate, now).getYears();