【发布时间】:2023-02-24 11:36:14
【问题描述】:
`我还在学习,我觉得我做这一切都是错的,但我需要一些帮助。我有一个任务需要让用户设置一周中的某一天,然后程序会让用户选择一个选项,返回当天、返回第二天、返回前一天,或者将某些天添加到这一天他们设置(例如:如果将日期设置为星期一并添加 4 天,则它将返回星期五)。我真的只需要添加天数部分的帮助,但任何关于如何使代码更好的建议都值得赞赏。
我想知道我是否可以将一个 int 值分配给一个字符串。例如,如果 String day 等于“Sunday”,则 int a = 1。我想将一周中的每一天分配给一个 int 值,然后将用户输入的任何数字添加到 int 值,然后总和将是新的天。
如果有更好的方法来做到这一点,请告诉我,这是我的代码(抱歉,如果它看起来不好)。
import java.util.Scanner;
public class Main
{
public static void main(String\[\] args)
{
Day.userInput();
}
}
class Day
{
static int b;
public static void userInput()
{
Scanner scan = new Scanner(System.in);
// set day of week
System.out.println("Please set the day of the week:");
String day = scan.nextLine();
if(day.equals("sunday") || (day.equals("Sunday")) )
{
b = 1;
}
if(day.equals("monday") || (day.equals("Monday")) )
{
b = 2;
}
if(day.equals("tuesday") || (day.equals("Tuesday")) )
{
b = 3;
}
if(day.equals("wednesday") || (day.equals("Wednesday")) )
{
b = 4;
}
if(day.equals("thursday") || (day.equals("Thursday")) )
{
b = 5;
}
if(day.equals("friday") || (day.equals("Friday")) )
{
b = 6;
}
if(day.equals("saturday") || (day.equals("Saturday")) )
{
b = 7;
}
System.out.println("Enter 1 to return the day.\nEnter 2 to return tomorrows day.\nEnter 3 to return yesterdays day.\nEnter 4 to add days to the current day.\n");
int a = scan.nextInt();
// return day
if(a == 1)
{
System.out.println("The day is " + day);
}
//return next day
if(a == 2)
{
if ( b == 1)
{
System.out.println("The next day is Monday.");
}
if (b == 2)
{
System.out.println("The next day is Tuesday.");
}
if (b == 3)
{
System.out.println("The next day is Wednesday.");
}
if (b == 4)
{
System.out.println("The next day is Thursday.");
}
if (b == 5)
{
System.out.println("The next day is Friday.");
}
if (b == 6)
{
System.out.println("The next day is Saturday.");
}
if (b == 7)
{
System.out.println("The next day is Sunday.");
}
}
//return previous day
if(a == 3)
{
if( b == 1)
{
System.out.println("The previous day was Saturday.");
}
if (b == 2)
{
System.out.println("The previous day was Sunday.");
}
if (b == 3)
{
System.out.println("The previous day was Monday.");
}
if (b == 4)
{
System.out.println("The previous day was Tuesday.");
}
if (b == 5)
{
System.out.println("The previous day was Wednesday.");
}
if (b == 6)
{
System.out.println("The previous day was Thursday.");
}
if (b == 7)
{
System.out.println("The previous day was Friday.");
}
}
// add days
if(a == 4 )
{
System.out.println("Enter the number of days you want to add");
int c = scan.nextInt();
}
}
}
我知道我可以做到这一点的方法,但它需要大量的行和 if 语句。 `
【问题讨论】: