用java 代码写个案例
时间: 2023-09-09 08:04:20 浏览: 63
### 回答1:
我可以写一个简单的Java代码示例,用来演示如何计算两个数字的和:
// Java program to add two numbers
class AddTwoNumbers
{
// Method to add two numbers
public static int addTwoNumbers(int num1, int num2)
{
return num1 + num2;
}
// Driver code
public static void main(String[] args)
{
int num1 = 5;
int num2 = 6;
// Print the result
System.out.println("Sum of num1 and num2 is: " + addTwoNumbers(num1, num2));
}
}
### 回答2:
题目:根据输入的年份判断是否为闰年
闰年的定义是能被4整除但不能被100整除,或者能被400整除的年份。请写一个Java程序,根据用户输入的年份判断是否为闰年并输出结果。
代码如下:
```java
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 提示用户输入年份
System.out.print("请输入年份:");
int year = scanner.nextInt();
// 使用条件判断来判断是否为闰年
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println(year + "年是闰年。");
} else {
System.out.println(year + "年不是闰年。");
}
}
}
```
运行程序后,用户将被提示输入一个年份。程序根据输入的年份进行判断,然后输出结果,告知用户输入的年份是否为闰年。
示例输出:
```
请输入年份:2020
2020年是闰年。
请输入年份:1900
1900年不是闰年。
```