gpt4 book ai didi

java - 在 Java 中生成空格

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:12 25 4
gpt4 key购买 nike

您好,我正在尝试生成空格,以便当 startDay == 2 或更多时第一行有空格。该程序应该模拟压延机因此,例如,如果有标题(星期一、星期二等),则空格将允许“1”(即日期 1)位于正确的.

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;
}
}
}

}
}

最佳答案

从你的行开始

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++;
}

关于java - 在 Java 中生成空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com