首页 > 解决方案 > How do I calculate years until graduation for a user's input?

问题描述

I'm new to Java and I would like to program something where the user inputs their graduation year (i.e 2032) and it would print out "You will graduate in 12 years." However with the code I have created, it only works for graduation years 2020 through 2029, not years after 2029.


import java.util.Scanner;
public class NameGames {
   public static void main(String[] args) {
   Scanner one = new Scanner(System.in);
   System.out.print("Enter graduation year: ");
   int gradYear = one.nextInt();
   
   System.out.println("You will graduate in " + untilGrad(gradYear) + " years.");
   }

   public static int untilGrad(int gradYear) {
      return (gradYear % 10);
   }
}

标签: java

解决方案


你的untilGrad方法应该是;

int year = Calendar.getInstance().get(Calendar.YEAR);
return gradYear-year;

你的目标是找出他们毕业前的年数。这涉及通过Calendar.


推荐阅读