您好我正在尝试生成空格,以便在startDay == 2或更多时 第一行有空格。该程序应该模拟日历 因此,例如,如果有标题(星期一,星期二等),空格将允许“1”(即日期 1)位于正确的日< / em>的
import java.io.*;
public class Lab_4 {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer daysInMonth=31;
Integer startDay = 1;
int daysInWeek;
// we catch IO exceptions if any are thrown.
try {
System.out.println("how many days are in the month?");
daysInMonth = Integer.parseInt(reader.readLine());
//validate input
while((daysInMonth >= 32) || (daysInMonth < 28)){
System.out.println("There can't be more than 31 days or less than 28 days, enter a
valid number");
daysInMonth = Integer.parseInt(reader.readLine());
}
System.out.println("what is the starting day of the month? 1=sun... 7=sat");
startDay = Integer.parseInt(reader.readLine());
//validate input
while((startDay > 7)){
System.out.println("There cannot be more days than 7 days in a week, enter a valid
number");
startDay = Integer.parseInt(reader.readLine());
}
}catch (IOException e){
System.out.println("Error reading from user");
}
daysInWeek = 1;
//print every seven days to a new line of calender
if (startDay == 1) {
for (int i = daysInWeek; i <= (daysInMonth); i++) {
daysInWeek ++;
System.out.printf("%-2d ",i);
if ( daysInWeek ==7) {
System.out.println();
daysInWeek = 1;
}
}
}
//create blank space if start day is 2
if (startDay == 2) {
for (int i = daysInWeek; i <= (daysInMonth); i++) {
daysInWeek ++;
System.out.print(" ");
System.out.printf("%-2d ",i);
if ( daysInWeek ==7) {
System.out.println();
daysInWeek = 1;
}
}
}
}
}
答案 0 :(得分:0)
从您的行开始
daysInWeek = 1;
尝试更改为
daysInWeek = 1; // Start point...
int offSet = 0; // an offset of 0 == SATURDAY
if (startDay != 7) {
offSet = (startDay == 1) ? 6 : startDay - 1; // SUNDAY goes far right.
}
for (int i = 0; i < offSet; i++) { // Here's that spacing you wanted.
System.out.print(" ");
}
// print every seven days to a new line of calender
for (int i = 1; i <= (daysInMonth); i++) {
System.out.printf("%-2d ", i);
if ((daysInWeek + offSet) % 7 == 0) { // Add the offset, perform mod 7.
System.out.println();
}
daysInWeek++;
}