2016-08-05 20 views
-1

如何減去出生年份和當前年份以顯示年齡?Java掃描儀和int不顯示年齡

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

使用user_input.nextInt()閱讀整數值,你不能字符串。減去和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) 
+0

謝謝!它完美的作品。 – cookieWarrior

+0

@Zell如果有效,請將答案標爲已批准 –

0

您可以使用這樣的事情也

LocalDate birthdate = LocalDate.of(YEAR, MONTH, DAY); 
    LocalDate now = LocalDate.now(); 
    int age = Period.between(birthdate, now).getYears(); 
+0

這對我來說是新的!感謝分享一些知識。我是編碼新手! – cookieWarrior