1. 程式人生 > >Java任意輸入年月日並判斷這天是星期幾

Java任意輸入年月日並判斷這天是星期幾

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;import java.util.Scanner;public class Datetest{
public static void main(String[] args){
System.out.println("請輸入三個以內的數字,並以#結束:");
Scanner input = new Scanner(System.in);
String str="";
StringBuffer sb = new StringBuffer();
Calendar calendar = Calendar.getInstance();
String weekd = "日一二三四五六";
while(!(str=input.next()).equals("#")){
sb.append(str+";");
}
String subs=sb.toString();
String[] arr = subs.split(";");
if(arr.length!=3){
System.out.println("輸入資料錯誤!");
}
else{
String date = arr[0]+"-"+arr[1]+"-"+arr[2];
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date datet = null;
try {
datet = f.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
calendar.setTime(datet);
int day = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println("這天是星期"+weekd.substring(day-1,day));
}
}
}