java - 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);
}
}
解决方案
你的untilGrad
方法应该是;
int year = Calendar.getInstance().get(Calendar.YEAR);
return gradYear-year;
你的目标是找出他们毕业前的年数。这涉及通过Calendar
.
推荐阅读
- javascript - 无法从 Storybook 中的 Vuex 商店读取
- c# - 应用 TextWrapping 后如何获得具有内联元素支持的 TextBlock 行?
- spring-boot - 使用代理进行 Springboot 协议测试
- javascript - 按钮 2 显示与按钮 1 显示相同的文本
- php - 如何将页面分配给子页面
- css - 如何在标题中添加图像而不是图标反应原生元素
- c++ - C ++从2个不同的向量中删除shared_ptr
- android - Android openGL ES 3 Vector3f 和 Matrix4f 类的替代品是什么?
- swift - 当我滚动 SwiftUI/Swift 时,图像在列表中消失
- regex - 如何匹配 $ 或 $$ 但如果它们是这些 <$ 和 <$$ 中的任何一个则不匹配