import java.util.Scanner; public class Day { private String day = null; String d
ID: 3661125 • Letter: I
Question
import java.util.Scanner;
public class Day {
private String day = null;
String days[] = { "Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat" };
public void setDay(String day)
{
this.day = day;
}
public void printDay()
{
System.out.println("Given day is " + getDay());
}
public String getDay()
{
return day;
}
public String getNextDay(String currDay)
{
String nextDay = null;
for (int i = 0; i < days.length; i++)
{
if (currDay.equalsIgnoreCase(days[i]))
{
if (i == days.length - 1)
{
nextDay = days[0];
break;
} else
{
nextDay = days[++i];
break;
}
}
}
return nextDay;
}
public String getPrevDay(String currDay)
{
String prevDay = null;
for (int i = 0; i < days.length; i++)
{
if (currDay.equalsIgnoreCase(days[i]))
{
if (i == 0)
{
prevDay = days[days.length - 1];
break;
}
else
{
prevDay = days[--i];
break;
}
}
}
return prevDay;
}
public String calDay(String currDay, int no)
{
String resDay = null;
no = no % 7;
for (int i = 0; i < days.length; i++)
{
if (currDay.equalsIgnoreCase(days[i]))
{
resDay = days[(i + no)%7];
break;
}
}
return resDay;
}
public static void main(String args[]) {
System.out.println("Enter the Day");
Scanner sc = new Scanner(System.in);
String day = sc.nextLine();
Day day2 = new Day();
day2.setDay(day);
day2.printDay();
System.out.println("Previous Day is " + day2.getPrevDay(day));
System.out.println("Next Day is " + day2.getNextDay(day));
System.out.println("Calculated Day is " + day2.calDay(day, 12));
}
}
// This is the code I have so far. It takes in a user input of "mon", "tues", "wed", etc. and Prints thegiven day, previous day, next day, and calculated day. I can't get the calculated day to output properly. There is supposed to be a user input number of days, say 13. So if I input "mon", it should ask me "number of calculated days" and when I put in "13" it should return "sun". Thanks for the help.
Explanation / Answer
A small change fixes this, indicated in red . jus remove that line it works perfect!!
public String calDay(String currDay, int no) {
String resDay = null;
no = no % 7; remove this line
for (int i = 0; i < days.length; i++) {
if (currDay.equalsIgnoreCase(days[i])) {
resDay = days[(i + no) % 7];
break;
}
}
return resDay;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.