Using methods and objects, but no arrays - java

I was here earlier before, and got pointed in the right direction. But I couldn't get the offered solution to work. It now mostly works, but i'm stuck on one part, and I'm not sure how to proceed. If anyone can point me to the right direction, i'll be grateful. I just need a hint, or pointers to something I'm not seeing.
I'm trying to add a random number of days, and determine what that adds up to. I know I have to have a counter that flips over after 7, but I've tried everything, and keep getting errors
import java.util.*;
public class pooped
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int day;
System.out.println(" Days of the week are numbered 1-7"+
"From Sunday to Saturday, enter a number now");
day = console.nextInt();
System.out.println(isWeek(day));
printday(day);
}
public static boolean isWeek(int day)
{
return day >= 0 && day <= 7;
}
static Scanner console = new Scanner(System.in);
public static void addDay()
{
int date;
System.out.println("Enter how many days you want to go forward.");
date = console.nextInt();
if (int date > 0)
{
int day = date + 1;
}
}
public static void printday(int day)
{
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
default:
break;
}
}
}

If you need
a counter that flips over after 7
consider using day = day % 7; in your main method, which gives you the modulo operation.

When you say "I have to have a counter that flips over after 7", do you mean that 7 should roll back to 0, 8 to 1, etc?
If that's the case, you need to look at the modulus operator (%)
You inWeek function looks incorrect. If your day is 0 based, it should be:
public static boolean isWeek(int day)
{
return day >= 0 && day < 7;
}
Otherwise you will have 8 days.

Related

Why does initializing a string in an if statement seem different than in a switch statement? [duplicate]

This question already has answers here:
Why do I get a "variable might not have been initialized" compiler error in my switch block?
(2 answers)
Closed 4 years ago.
I'm learning Java and I'm making simple programs to find the season that a month is in, based off some book examples. These two classes demonstrate two ways of testing a value: if/else if statement, and switch statement. The thing I'm confused with is the string that is used to hold the season. When I declare it as just String season; it works with the if statements. But with the switch statement, doing that produces a "The local variable season may not have been initialized" error.
public class IfElse {
public static void main(String args[]) {
int month = 5;
String season;
// isn't initialized, works fine
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else
season = "Fall";
// this is okay
System.out.println("May is a " + season + " month.");
}
}
Not initializing season at the same time as declaration works fine for the above code, but the season variable in the last println() for the switch produces an error if it's declared the same way.
The following code doesn't work:
public class Switch {
public static void main(String args[]) {
int month = 5;
String season;
// HAS to be initialized, currently causes error
switch(month) {
case(12):
case(1):
case(2):
season = "Winter";
break;
case(3):
case(4):
case(5):
season = "Spring";
break;
case(6):
case(7):
case(8):
season = "Summer";
break;
case(9):
case(10):
case(11):
season = "Fall";
break;
default:
System.out.println("Invalid month");
break;
}
System.out.println("May is a " + season + " month");
} // produces an error if season isn't initialized to null or ""
}
What causes this? Is it the braces enclosing the switch statement, or a problem with the switch statement itself? How is initializing a string inside an if statement any different than initializing it inside a switch statement? I just can't seem to understand this.
Sorry if this is extremely obvious or if it seems like a dumb question.
That is because you did not specify what season has to be in the default case. What happens when month is not within 1-12? season will not be initialized.
If you are expecting strictly only 1-12 as month input, then you might want to consider throwing an Exception in default:
default:
throw new IllegalArgumentException("Invalid month");
In your first example, there is no path through the code that fails to assign a value to 'season'. In the second example, the default case does not assign a value, so the last print ("May is...") can be executed with an uninitialized value.
In your if/else code, there is an assurance that the variable season will get a value. That is, the else statement.
Your switch code does not have it. Look what will happen to the variable season if the given value for month is 13 -- it will not get a value, and will remain un-initialised.
You should use this
public class Switch {
public static void main(String args[]) {
int month = 5;
String season;
// HAS to be initialized, currently causes error
switch(month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6 :
case 7 :
case 8 :
season = "Summer";
break;
case 9 :
case 10 :
case 11 :
season = "Fall";
break;
default:
season = "Invalid";
break;
}
System.out.println("May is a " + season + " month");
} // produces an error if season isn't initialized to null or ""
}

If-Else program for days of the week

I need help with homework. I need to write a program that will use if else statements instead of the switch statement shown:
switch (day) {
case 1: case 2: case 3: case 4:
message = "regular workday";
break;
case 6: case 7:
message = "weekend";
break;
default:
message = "tgif";
}
I need to allow the user to key in the day of the week and then display the corresponding output. I also need to make sure it tests the input for a valid number (1-7). The user needs to be able to enter as many different days as they would like and to have a value (-1) end the program when entered.
I have this so far:
public class Question1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int day;
do {
System.out.println("What day of the week do you want to enter? When finished, please enter \"-1\".");
day = input.nextInt(); //User input assigned to variable day
if (day == 1 || day == 2 || day == 3 || day == 4) {
System.out.println("Regular workday");
}
else if (day == 6 || day == 7) {
System.out.println("Weekend");
}
else if (day == 5) {
System.out.println("TGIF");
}
else {
System.out.println("Invalid Month. Please try again or enter \"-1\" when finished.");
}
} //end do
while (day != -1); //Loops when input meets the criteria
}
}
PROBLEM: The problem I am having is that when I enter -1 to end the program, it takes it as an else and prints the else statement when I simply just want the program to end.
Try replacing the line else { with else if (day != -1) {. This will trigger the branch for any number that didn't satisfy the previous conditions, or being -1
You can re-test your input while inside the else-block and return false and/or jump to quitProgram-part - before showing the error message.

Having problems with consistency [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having issues with my program. Namely in that when I enter a value to say what day it will be a few days from now, it sometimes work, and other times it doesn't. I'm not sure what the problem is... Bear with me I'm still learning.
Thanks in advance
import java.util.*;
public class pooped {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int day;
int june;
int dates;
System.out.println(" Days of the week are numbered 0 - 6 " +
"From Sunday to Saturday, enter a number now");
day = console.nextInt();
int kill = day;
System.out.println("Enter the number of days forward: ");
dates = console.nextInt();
printday(day);
day = addDay(day);
printday(day);
day = removeDay(day);
printday(day);
dates = count(dates);
printday(kill + dates);
}
public static int count(int dates) {
if (dates > 6){
dates = (dates % 6);
}
System.out.println("That many days out is: ");
return dates;
}
private static int addDay(int day) {
day++;
System.out.println("The next day is: ");
if (day > 6) {
day = 0;
}
return day;
}
private static int removeDay(int day) {
day = day - 2;
System.out.println("The previous day is: ");
if (day == 0) {
day = 6;
}
return day;
}
public static boolean isWeek(int day) {
return day >= 0 && day <= 6;
}
public static void printday(int day) {
switch (day)
{
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
default:
break;
}
}
}
You should mod by 7, not 6. Modding by 6 will only yield values 0-5.
dates %= 7;
So, whenever you add or subtract from a variable that should remain between 0-6, perform the above mod, by 7.
Full source
public class Main {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int day;
int june;
int dates;
System.out.println(" Days of the week are numbered 0 - 6 "
+ "From Sunday to Saturday, enter a number now");
day = console.nextInt();
System.out.println("Enter the number of days forward: ");
dates = console.nextInt();
printday(day);
printday(addDay(day));
printday(removeDay(day));
printday(day + count(dates));
}
public static int count(int dates) {
dates %= 7;
System.out.println("That many days out is: ");
return dates;
}
private static int addDay(int day) {
day++;
day %= 7;
System.out.println("The next day is: ");
return day;
}
private static int removeDay(int day) {
day--;
day += 7;
day %= 7;
System.out.println("The next day is: ");
return day;
}
public static boolean isWeek(int day) {
return day >= 0 && day <= 6;
}
public static void printday(int day) {
switch (day) {
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
default:
break;
}
}
}

Can same Scanner object take inputs of different datatypes? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Here's my code:
package Random;
import java.util.Scanner;
public class SwitchMonth {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Year: ");
int year = in.nextInt();
System.out.println("Enter month: ");
String month = in.nextLine();
//String month = ""
switch (month) {
case "january":
case "march":
case "may":
case "july":
case "august":
case "october":
case "december":
System.out.println("No. of days: 31");
break;
case "april":
case "june":
case "september":
case "november":
System.out.println("No. of days: 30");
break;
case "february":
if ((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0))
System.out.println("No. of days: 29");
else
System.out.println("No. of days: 28");
break;
default:
System.out.println("Wrong month entered.");
break;
}
in.close();
}
}
Output:
Enter year: 2000
Enter month:
Wrong month entered.
The program terminates without taking the month input.
If i hard code the month name then it's working fine but when i take the input from console it terminates with above output. I believe the problem lies with Scanner object.
If i use another Scanner object for month then it's working fine.
So my question is: Can i use same scanner object for taking int input then string input or not??
if not then why??
All the answers are appreciated. Thanks in advance.
nextInt() does not consume the ENTER after the year is entered, so nextLine() consumes it, leaving you with an empty string. One way around this is to always use nextLine():
int year = Integer.valueOf(in.nextLine());
Alternatively, you can just use another nextLine() after consuming the int:
int year = in.nextInt();
in.nextLine(); // To get rid of the additional \n

Whether it is correct to take 01/01/0001 date as Monday?

I am writing a program to display the Day for the given date. (E.g. Thursday for 1/1/1970.)
While attempting that I have some problems.
This is my program.
/*Concept:
The noOfDays variable will count the no of days since 01/01/0001. And this will be Day one(1). E.g
noOfDays = 365 for 01/12/0001 and noOfDays = 731 for 01/01/0003 and so on....
Since I taken Monday as 01/01/0001,the day of the specific date can be achieved by switching(noOfDays%7)
E.g. 365 % 7 = 1. So, the 365th day is monday...
*/
import java.util.Scanner;
class DayDisplayer
{
long noOfDays;
int month;
int days;
int year;
Scanner scan;
int countYear;
int countMonth;
DayDisplayer()
{
scan = new Scanner(System.in);
noOfDays = 0;
System.out.println("Enter the date please");
days = scan.nextInt();
month = scan.nextInt();
year = scan.nextInt();
System.out.println("Your Date is: "+days+"/"+month+"/"+year);
}
boolean leapYearCheck(int year)
{
if( ((year%100 == 0) && (year%400 != 0)) || (year%4 != 0) ) // when it is divisible by 100 and not by 400.
return false;
else
return true;
}
boolean isThere31Days()
{
if ( ( (countMonth >> 3) ^ (countMonth & 1) ) == 1 )
return true;
else
return false;
}
void getDaysThatInDays()
{
noOfDays += days;
}
void getDaysThatInMonth()
{
countMonth = 1;
while(countMonth<month)
{
if( countMonth == 2 )
if( leapYearCheck(year) == true)
noOfDays += 29;
else
noOfDays += 28;
else
if ( isThere31Days())
noOfDays += 31;
else
noOfDays += 30;
countMonth++;
}
}
void getDaysThatInYear()
{
countYear = 1;
while(countYear<year)
{
if( leapYearCheck(countYear)== true )
noOfDays += 366;
else
noOfDays += 365;
countYear ++;
}
}
void noOfDaysAndDayName()
{
System.out.println("The noOfDays is"+noOfDays);
System.out.println("And Your Day is :");
int day;
day = (int)(noOfDays%7);
switch(day)
{
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
}
}
}// end of MonthToDate class
public class Main
{
public static void main(String args[])
{
DayDisplayer dd= new DayDisplayer();
dd.getDaysThatInYear();
dd.getDaysThatInMonth();
dd.getDaysThatInDays();
dd.noOfDaysAndDayName();
}
}
In this code ,when I take 01/01/0001 as Monday and calculated the other days. And I am getting correct answers.
But In www.timeanddate.com website they took 01/01/0001 as Saturday.
But still for the other recent dates (say 17/7/2011) they are giving the correct answer (as Sunday).
I could guess these lags are due to the migration of Julier system to Gregorian system.
But I have a doubt whether my approach of calculating the Days from 0001 year is correct or not?
Also I have a doubt about whether to take 01/01/0001 date is Monday or Saturday.
(And If I took Saturday as my first day, I am getting wrong answers.)
someone please explain.
Thanks in advance.
One problem could be highlighted by an off-by-one error your opening comment:
The noOfDays variable will count the no of days since 01/01/0001. E.g
noOfDays = 365 for 01/12/0001 and noOfDays = 731 for 01/01/0003 and so on.
That says that 0001-01-01 will be day 0 (0 days since the reference date), which in turn means that 0001-12-31 on your proleptic Gregorian calendar will be 364, not 365.
You can adjust this in either of two ways:
Define that 0001-01-01 will be day 1 (whereupon the rest of the quoted fragment of comment is correct).
Change the comment values to 364 and 730.
Another problem with reverse engineering dates back that far is understanding the 'proleptic' Gregorian calendar. The term strictly means 'the representation of a thing as existing before it actually does or did so', and applies forward, but the term is also used in calendrical calculations to refer to applying the present rules backwards in time. The issue at hand is that the Gregorian calendar with its rules for leap years (divisible by 400, or divisible by 4 but not divisible by 100) did not exist in year 1. And the question is: did the web sites you referred to compensate for the switch between the Julian calendar and the Gregorian? (Underlying that are a lot of complications; the calendar was exceptionally volatile, even in the Roman Empire, between about 55 BCE and 200 CE.)
An excellent book for considering matters of date is Calendrical Calculations.
You could always compare to what Java itself gives you:
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.FieldPosition;
public class Test {
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the date please");
int days = scan.nextInt();
int month = scan.nextInt();
int year = scan.nextInt();
SimpleDateFormat sdf = new SimpleDateFormat("E dd-MM-yyyy G");
StringBuffer buf = new StringBuffer();
Calendar cal = new GregorianCalendar();
cal.set(year, month-1, days);
sdf.format(cal.getTime(), buf, new FieldPosition(0));
System.out.println(buf.toString());
}
}
So we get:
> java Test
Enter the date please
1
1
0001
Sat 01-01-0001 AD
which seems to agree with the website...

Categories