0
我想根據當前日期和用戶輸入將來的天數來計算,日曆中的一週中的哪一天。例如,今天是星期五,也就是我的節目中的第5天。如果用戶提前15天進入,我希望當天打印的是星期六(距今天15天)。不幸的是,無論提前多少天,我都會得到星期五的結果。有人可以幫助這個嗎?謝謝。根據用戶輸入計算一天:總是返回當天
到目前爲止的代碼:
import java.util.*;
import java.text.SimpleDateFormat;
public class DayCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userEntryInt;
String dayName;
String userEntry;
String weekdayName = new SimpleDateFormat
("EEEE", Locale.ENGLISH).format(System.currentTimeMillis());
System.out.println("Today is "+weekdayName+".");
System.out.println("Please enter how many days in the past or future "+
"of which you'd like to know the day.");
userEntry = sc.next();
userEntryInt = Integer.parseInt(userEntry);
dayName = getDayNumber(weekdayName, userEntryInt);
System.out.println("Your selected day is a " + dayName +".");
}
//method to calculate new day based on user entry
public static String getDayNumber(String name, int userNumber)
{
String dayNumber = "TEST";
int dayResult = 0;
int dayNumberInt;
switch (name){
case "Monday":
dayNumber = "1";
break;
case "Tuesday":
dayNumber = "2";
break;
case "Wednesday":
dayNumber = "3";
break;
case "Thursday" :
dayNumber = "4";
break;
case "Friday":
dayNumber = "5";
break;
case "Saturday":
dayNumber = "6";
break;
case "Sunday":
dayNumber = "7";
}
System.out.println(dayNumber); //test
dayNumberInt = Integer.parseInt(dayNumber);
System.out.println("dayNumberInt is "+dayNumberInt);//test
System.out.println("dayResult is "+dayResult);//test
if(((dayNumberInt+userNumber)/7)<7)
{
dayResult = dayNumberInt+dayResult;
}
else if (((dayNumberInt+userNumber)/7)>7)
{
dayResult = dayNumberInt-dayResult;
}
if (dayResult <0)
{
dayResult = -dayResult;
}
if (dayResult==0)
{
dayResult = dayNumberInt;
}
String dayNameResult="";
switch (dayResult){
case 1: dayNameResult = "Monday";
break;
case 2: dayNameResult = "Tuedsay";
break;
case 3: dayNameResult = "Wednesday";
break;
case 4: dayNameResult = "Thursday";
break;
case 5: dayNameResult = "Friday";
break;
case 6: dayNameResult = "Saturday";
break;
case 7: dayNameResult = "Sunday";
break;
}
return (dayNameResult);
}
}
我會建議看''%運營商,這將使你的餘數(所以'15%7 = 1'),這可能是比7 – Gliderman
而不是'userEntry = SC將更加容易。下一個(); userEntryInt = Integer.parseInt(userEntry); '只需使用'userEntryInt = sc.nextInt(); ' –