编程一个程序,计算今天是今年的第几天.
分析:本题可以通过一个switch语句来进行计算,case中的常数表达式的值可以逆序输入,并且不加break语句,只在最后一个后面加上break,这样就可以实现累加。需要注意的是闰年二月份的天数,只需要在二月份的时候加上判断语句来判断当年是否为闰年。
最后可以在外面加上一个while循环来实现多次运行。
import java.util.Scanner;
public class home2 {
public static void main(String[] args) {
int year,month,day;
int flag = 1;
while (flag==1)
{
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
year = scanner.nextInt();
System.out.println("请输入月份:");
month = scanner.nextInt();
System.out.println("请输入日:");
day = scanner.nextInt();
switch (month-1)
{
case 11: day += 30;
case 10: day += 31;
case 9: day += 30;
case 8: day += 31;
case 7: day += 31;
case 6: day +=30;
case 5: day += 31;
case 4: day += 30;
case 3: day +=31;
case 2: if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
day += 29;
}
else {
day += 28;
}
case 1: day += 31;
case 0:break;
default:
System.out.println("月份输入有误!");
}
System.out.println("今天是"+year+"年第"+day+"天");
System.out.println("请问是否继续?(输入1继续,0退出)");
flag = scanner.nextInt();
}
}
}
运行结果如下:
输出2-100以内所有的质数.
用Java来编写输出质数的算法可以与C语言的中的函数调用类似,编写一个函数,然后主函数调用来实现质数的判断并输出。在Java中称为方法。
public class home3 {
public static void main(String[] args) {
for (int i = 2; i <=100 ; i++) {
boolean a = home3.Su(i);
if (a){
System.out.println(i);
}
}
}
public static boolean Su(int i){
for (int j = 2; j < i; j++) {
if (i%j==0){
return false;
}
}
return true;
}
}
当然可以通过下面的方法来实现任何数字的判断。