用Java做一个题:输出一个年月日,得出这个日子是这一年的多少天?请高手赐教

2024-12-03 16:39:03
推荐回答(3个)
回答(1):

import java.util.Scanner;
public class Aasf {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
System.out.println("请输入年");
int Y=input.nextInt();
System.out.println("请输入月");
int M=input.nextInt();
System.out.println("请输入日");
int D=input.nextInt();
int pdM,sum=0;
if((Y%4==0&&Y%100!=0)||Y%400==0){
for(pdM=1;pdM<=M;pdM++){
switch(pdM){
case 1:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 2:if(M>pdM){sum+=29;}else{sum+=D;}break;
case 3:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 4:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 5:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 6:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 7:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 8:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 9:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 10:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 11:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 12:if(M>pdM){sum+=31;}else{sum+=D;}break;
}
}
}
else{
for(pdM=1;pdM<=M;pdM++){
switch(pdM){
case 1:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 2:if(M>pdM){sum+=28;}else{sum+=D;}break;
case 3:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 4:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 5:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 6:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 7:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 8:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 9:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 10:if(M>pdM){sum+=31;}else{sum+=D;}break;
case 11:if(M>pdM){sum+=30;}else{sum+=D;}break;
case 12:if(M>pdM){sum+=31;}else{sum+=D;}break;
}
}
}
System.out.println(sum);
}
}

回答(2):

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class W {

private static final SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
private static final Calendar cd=Calendar.getInstance();
public static void main(String[] args) throws Exception {
System.out.print("请以 yyyy-MM-dd 的格式输入一个日期 ->:");
byte[] buff=new byte[128];
int r=System.in.read(buff);
String ds=new String(buff,0,r).trim();
long time=df.parse(ds).getTime();
cd.setTimeInMillis(time);
int dy=cd.get(Calendar.DAY_OF_YEAR);
System.out.println(ds+" 是当年的第 "+dy+" 天");
}
}

回答(3):

最酷、最简练的实现方式:
Scanner是1.5的新特性,用就用最新的。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int a=0,b=0,i;
System.out.print("输入数字以空格分开按回车结束输入:");
Scanner scan =new Scanner(new Scanner(System.in).nextLine());
while(scan.hasNext()){
i=scan.nextInt();
if(i%2!=0)
a+=i;
else
b+=i;
}
scan.close();
System.out.println("奇数和是:"+a+" 偶数和是:"+b);
}
}

如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!

vaela