我试图编写一个程序,通过给出一个数字来计算一周中的几天。我想写这个不使用Arrays。,或枚举类型,只是方法我该怎么做?我也希望能够将一周中的某一天设定为起点。
谢谢
public static void main(String[] args);
{
int sunday, monday, tuesday, wednesday, thursday, friday, saturday;
int week;
int day;
System.out.println(" Day of the week is" + day);
public void count()
public void week()
public void printday()
public void nextday()
public void previousday()
我不是最好的,但我认为练习是完美的
答案 0 :(得分:1)
这看起来像是家庭作业,但如果你不打算使用天数,我猜你可以使用switch
语句和一周中的日子。
此特定样本从第3天(0为星期一)到第14天进行迭代。
for (int i = 3; i < 15; i++) {
String s = null;
switch (i % 7) {
case 0: s = "Monday"; break;
case 1: s = "Tuesday"; break;
case 2: s = "Wednesday"; break;
case 3: s = "Thursday"; break;
case 4: s = "Friday"; break;
case 5: s = "Saturday"; break;
case 6: s = "Sunday"; break;
}
System.out.println(s);
}
答案 1 :(得分:1)
如果我正确理解你的问题,这应该是你的伎俩:)
/**
*
* @param startingDay
* - day of the week starting point ( need to be between 0-6 )
* @param noDays
* number of days to count
* @return result Day of the week
*/
private static String getWeekDay(int startingDay, int noDays) {
int dayNr = noDays % 7;
int finalDayNr = (startingDay + dayNr) % 7;
return getDay(finalDayNr);
}
private static String getDay(int dayNr) {
switch (dayNr) {
case 0:
return "SUNDAY";
case 1:
return "MONDAY";
case 2:
return "TUESDAY";
case 3:
return "WEDNESDAY";
case 4:
return "THURSDAY";
case 5:
return "FRIDAY";
case 6:
return "SATURDAY";
}
throw new IllegalArgumentException("Wrong input. Day nr must be between 0-6.");
}
并且没有ENUM的版本,但Enum版本是可取的......从您可能想到的任何角度来看。
public static void main(String[] args) {
System.out.println(getWeekDay(0, 15));
System.out.println(getWeekDay(1, 15));
System.out.println(getWeekDay(5, 3));
}
使用示例(针对这两种方法中的任何一种):
{{1}}
答案 2 :(得分:-1)
public static void main(String[] args) {
int day = 1;
System.out.println(isWeek(day));
printday(day);
}
public static boolean isWeek(int day) {
// Sunday or Saturday
if (day == 1 || day == 7) {
return false;
}
return true;
}
public static void printday(int day) {
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
// Until Saturday
default:
break;
}
}
代码错误,但没有那样的数组或枚举?