I am currently trying to finish this program, however when I am testing my switch statement, it goes directly to my default case and says that I have entered invalid information.
My Task
I have to receive a month from the user and send it to my case statement in order to execute my code for the certain case. As you may notice, that each case has a key in it, this key is for personal purposes. Please disregard.
My Problem
case statement goes directly into my default statement, which issues an invalid information message to the user.
My Progress
This will be my complete program, everything seems to work properly except that my case statement recognizes every month as invalid input
// Import Libraries
import javax.swing.*;
import java.util.*;
import java.io.*;
// This is my program.
public class DateCalc
{
public static void main (String[] args)
{
String month;
String day;
String inputYear;
Scanner keyboard = new Scanner(System.in);
// receiving input for my age variable
System.out.print( "Please Enter The Month Of The Date :");
month = keyboard.nextLine();
// receiving input for my weight variable
System.out.print( "Please Enter The Day Of The Date : ");
day = keyboard.nextLine();
// receiving input for my height variable
System.out.print( "Please Enter The Year OF The Date : ");
inputYear = keyboard.nextLine();
String stringYear = ""+ inputYear.charAt(inputYear.length()-2) + inputYear.charAt(inputYear.length()-1);
int year = Integer.parseInt(stringYear);
int intDay = Integer.parseInt(day);
switch(month)
{
// I tried to test my program by using my first case " January ", However it goes right through every case directly for my default case.
case "January || january" :
int janKey = 1;
int janQuarter = year / 4;
int janSum = year + janQuarter + intDay + janKey;
System.out.print( " Date Entered Was : " + month + ","+ day + "" + inputYear);
System.out.print( " Last Two Digits Of The Year Were : " + year);
System.out.print( " One Quarter Of Last Two Digits : " + janQuarter);
System.out.print( " The Given Day Of The Month Entered : " + day);
System.out.print( " The Index Key This Moth is : " + janKey);
System.out.print( " The Sum Of All The number Above is : " + janSum);
System.out.print( " \n \n The Day Of The Week Was : ");
int weekDay = dayLookUp(janSum);
System.out.print( " \n \n The Day Of The Week Was : " + weekDay);
break;
case "February || february":
int febKey = 4;
break;
case "March || march":
int marKey = 4;
break;
case "April || april":
int aprKey = 0;
break;
case "May || may":
int maykey = 2;
break;
case "June || june":
int junKey = 5;
break;
case "July || july":
int julKey = 0;
break;
case "August || august":
int augKey = 3;
break;
case "September || september":
int septKey = 6;
break;
case "October || october":
int octKey = 1;
break;
case "November || november":
int novKey = 4;
break;
case "December || december":
int decKey = 4;
break;
// IN MY DEFUALT CASE " inputValidation " WILL BE EXECUTED
default:
JOptionPane.showMessageDialog(null," Invalid Entry Please Try Again " );
}
}
public static int dayLookUp ( int janSum )
{
int sum = janSum;
int day = 14 % 7;
return day;
}
}
The way you're doing it now, it's looking for the whole string as is, literally, not interpreting the || as any form of or.
You can either set the element in the switch to uppercase or lowercase use :
switch(month.toLowerCase()) {
case "january" :
...
break;
case "february":
...
...
}
or you have to double case elements:
switch (month) {
case "January":
case "january":
...
break;
case "February":
case "february":
...
...
}
The mistake is at "January || january" this is one String use case "January": case "january":
You cannot test for alternatives this way, case "January || january": doesn't work. You can give alternatives with multiple cases
switch (month) {
case "january":
case "January":
int janKey = 1;
without an intervening break. This causes a fall through to the second case, when january is entered. The same is with the other months, of course.
Related
How do i take the user inputted day, month and year then store in a dd-mm-yyyy format? I can get everything to work except combining them into a date and storing them in the startDate variable. I also don't think startMonth will be accessible as it's in a switch case but I'm very new to java and unsure.
public static void carBookingDates() {
int carNumber;
int startYear;
int startDay;
int startMonth;
int daysInMonth = 0;
int endYear;
int endMonth;
int endDay;
Scanner input = new Scanner(System.in);
System.out.println("To make a booking:");
System.out.printf(" Select a car number from the car list: ");
carNumber = input.nextInt();
System.out.println("");
System.out.println("Enter a booking start date.");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
while (startYear < 2022 || startYear > 2030) {
System.out.println("Invalid year, please try again: ");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
}
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
while (startMonth < 1 || startMonth > 12) {
System.out.println("Invalid month, please try again: ");
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
}
switch (startMonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
break;
case 2:
if (((startYear % 4 == 0)
&& !(startYear % 100 == 0))
|| (startYear % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
while (startDay > daysInMonth || startDay <= 0) {
System.out.println("Invalid day, plese try again");
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
LocalDate startDate() = LocalDate.parse(startDay + "-" + StartMonth "-" + startYear);
}
}
First of all, you can use the Java 8 Date Time API to get the number of days in a month instead of using a manual switch case for making the code more readable.
import java.time.YearMonth;
Then:
// 2021 is the year and 2 is the month
int daysInMonth = YearMonth.of(2021,2).lengthOfMonth());
Now to form the date in dd-mm-yyyy format :
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Then:
// pass your date value here under LocalDate.of method
LocalDate.of(2021,2,16).format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
import java.util.Scanner;
public class DaysInMonth
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:")
int year = input.nextInt(); enter code here
System.out.print("Enter a month:");
int month = input.nextInt(); enter code here
int days = 0;
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0)||(year % 400 == 0);
switch (month){
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " +days+ " Days in Month "+month+ " of Year " +year+ ".\n";
System.out.println(response); // new line to show the result to the screen.
}
}
Why can't I type in January to get the same output result if I type 1? It should print "There are 31 days in the month of January of Year 2018" I initialized the month so it should read January or any other month.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
You can use Strings in a switch statement to check for several equivalent cases:
switch (monthInput.toLowerCase()) {
case "january":
case "jan":
case "1":
days = 31;
break;
case "february":
case "feb":
case "2":
days = isLeapYear ? 29 : 28;
break;
case "march":
case "mar":
case "3":
days = 31;
break;
// etc.
default:
System.out.println(monthInput + " is not a valid month");
input.close();
System.exit(0);
}
But this means you have to read your input as a String, not as an int...
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); // enter code here
input.nextLine(); // read the rest of the line (if any)
System.out.print("Enter a month:");
String monthInput = input.nextLine();
Note the use of input.nextLine(); after the .nextInt() — this is because the nextInt() call does not consume all of the input, it only reads the int that you typed for the Year, it does not read the newline (enter key), so you have to read that to be ready to read the next input, which is the month number or name.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
A simple approach is to use name array
// before main.
static final String[] MONTH = "?,Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");
// inside main
String monthStr = MONTH[month];
Add the full month names as needed.
I'm trying to get the System.out.print on the same line. I want to have the cases as just days (case 0: "Sunday") so I can write System.out.println( "Today is "+ day + " and the future day is " + m1) but when I try this, I get the case number instead of the string (Today is 0 and the future day is 0). I think there's a better way to write the logic compared to the way I have it:
import java.util.*;
public class HomeWork3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Sun = 0, Mon = 1, Tue = 2, Wed = 3, Thurs = 4, Fri = 5, Sat = 6 ");
System.out.print("\nEnter today's number: ");
int day = input.nextInt();
System.out.print("Enter the number of days that elapsed since today: ");
int n1 = input.nextInt();
//String strD = Integer.toString(day);
switch (day){
case 0: System.out.println("Today is Sunday");
break;
case 1: System.out.println("Today is Monday");
break;
case 2: System.out.println("Today is Tuesday");
break;
case 3: System.out.println("Today is Wednesday");
break;
case 4: System.out.println("Today is Thursday");
break;
case 5: System.out.println("Today is Friday");
break;
case 6: System.out.println("Today is Saturday");
break;
}
int m1 = ((day + n1)% 7);
switch (m1){
case 0: System.out.println("The future day is Sunday");
break;
case 1: System.out.println("The future day is Monday");
break;
case 2: System.out.println("The future day is Tuesday");
break;
case 3: System.out.println("The future day is Wednesday");
break;
case 4: System.out.println("The future day is Thursday");
break;
case 5: System.out.println("The future day is Friday");
break;
case 6: System.out.println("The future day is Saturday");
break;
}
//String strD = Integer.toString(day);
//System.out.println(strD + " this might work " + n1);
}
}
OUTPUT:
Sun = 0, Mon = 1, Tue = 2, Wed = 3, Thurs = 4, Fri = 5, Sat = 6
Enter today's number: 2
Enter the number of days that elapsed since today: 5
Today is Tuesday
The future day is Sunday
How about the following:
String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int m1 = ((day + n1)% 7);
String output = String.format("Today is %s, the future day is %s", days[day], days[m1]);
System.out.println(output);
(Obviously you need to ensure day<7)
The easiest way is when you change the println() in the first switch-block to print() and add a space to your text.
A second version is to define two Strings and set the values in the switch-blocks:
String today;
switch (day){
case 0: today = "Sunday";
break;
and so on and also
String futureday;
switch (m1){
case 0: futureday = "Sunday";
break;
and so on. At last you have your desired output:
System.out.println("Today is "+ today + " and the future day is " + futureday);
But the most elegant way is to define an array of weekdays:
String[] days = {"Sunday","Monday","Tuesday"};
So you can delete your switch-blocks and simply write:
System.out.println("Today is "+ days[day] + " and the future day is " + days[m1]);
Hint: You have to initialize day and futureday. And you should check, that day is < 7 to prevent an IndexOutOfBounds-Exception.
How about simply using the built-in DayOfWeek enum:
int day = 4;
System.out.println("Today is " + DayOfWeek.of(day)
.getDisplayName(TextStyle.FULL, Locale.getDefault()));
Output:
Today is Thursday
But if you want to use a switch statement, I'd say, add a layer of abstraction, to simplify the problems you need to solve. e.g. make a method that takes and int and returns the day of the week as a String:
public static String getWeekDay(int dayNumber) {
switch(dayNumber) {
case 0: return "Sunday";
case 1: return "Monday";
case 2: return "Tuesday";
...
}
throw new IllegalArguemntException("Invalid day number: " + dayNumber);
}
And use that to create the output:
System.out.println("Today is " + getWeekDay(day));
Because you need to associate int and String you can use a map
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//add all days into the map with their key (number)
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "Sunday");
map.put(1, "Monday");
map.put(2, "Tuesday");
map.put(3, "Wednesday");
map.put(4, "Thursday");
map.put(5, "Friday");
map.put(6, "Saturday");
//Printing all days
for(int key : map.keySet()){
System.out.print(key+"="+map.get(key)+", ");
}
System.out.print("\nEnter today's number: ");
int day = input.nextInt();
System.out.print("Enter the number of days that elapsed since today: ");
int n1 = input.nextInt();
n1 = ((day + n1)% 7);
System.out.println("Today is "+map.get(day) + ", the future day is " + map.get(n1));
}
It allows you to get back the value which corresponds to the key entered with rhe scanner
I'm working on using enum / switch case along with Zeller's formula for saying what day of the year a specific date will be. My code was printing the right days before I implemented the enum / switch portion of my code (below). After I put in the enum/ switch case, when I run it in DrJava it does prompt for the day, the month and the year, but nothing prints once it goes through the switch case
import java.util.*;
public class Zeller {
public enum DaysOftheWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
private static int value;
public Zeller (int value){
this.value = value;
}
public int getValue(){
return this.value;
}
public static void main(String[] args) {
DetermineDay(value); // Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a year, month and a day
System.out.print("Enter month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the day of the month: 1-31: ");
int day = input.nextInt();
System.out.print("Enter year (e.g., 2008): ");
int year = input.nextInt();
// Check if the month is January or February
// If the month is January and February, convert to 13, and 14,
// and year has to -1. (Go to previous year).
if (month == 1 || month == 2) {
month += 12;
year--;
}
// Compute the answer
int k = year % 100; // The year of the century
int j = (int)(year / 100.0); // the century
int q = day;
int m = month;
int h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0)
+ (int)(j / 4.0) + (5 * j)) % 7;
value = h;
System.out.println(value);
}
public static String DetermineDay(int value){
String result = "Day of the week is ";
switch (value){
case 1 :
System.out.println(result + "Sunday");
break;
case 2 :
System.out.println(result + "Monday");
break;
case 3:
System.out.println(result + "Tuesday");
break;
case 4:
System.out.println(result + "Wednesday");
break;
case 5:
System.out.println(result + "Thursday");
break;
case 6:
System.out.println(result + "Friday");
break;
case 7 :
System.out.println( result + "Saturday");
break;
default :
System.out.println ("Looks like that day doesn't exist");
break;
}
return result;
}
}
If you want to output the day using DetermineDay you need to call that method at the end after you did the calculation and assigned the result to value.
This seems to work but there is a problem in your algorithm when trying this program with the date 4/11/2016 it does find that it is a Friday, but when using the date 5/5/2016 which is today the output is ¨Looks like that day doesn't exist¨, so yeah there is that.
At the end of DetermineDay you dont need to return a result since you already sop the result inside the switch.
import java.util.*;
public class Zeller {
public enum DaysOftheWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
private static int value;
public Zeller (int value){
this.value = value;
}
public int getValue(){
return this.value;
}
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a year, month and a day
System.out.print("Enter month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the day of the month: 1-31: ");
int day = input.nextInt();
System.out.print("Enter year (e.g., 2008): ");
int year = input.nextInt();
// Check if the month is January or February
// If the month is January and February, convert to 13, and 14,
// and year has to -1. (Go to previous year).
if (month == 1 || month == 2) {
month += 12;
year--;
}
// Compute the answer
int k = year % 100; // The year of the century
int j = (int)(year / 100.0); // the century
int q = day;
int m = month;
int h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0) + (int)(j / 4.0) + (5 * j)) % 7;
value = h;
System.out.println(value);
DetermineDay(value);
}
public static void DetermineDay(int value){
String result = "Day of the week is ";
switch (value){
case 1 :
System.out.println(result + "Sunday");
break;
case 2 :
System.out.println(result + "Monday");
break;
case 3:
System.out.println(result + "Tuesday");
break;
case 4:
System.out.println(result + "Wednesday");
break;
case 5:
System.out.println(result + "Thursday");
break;
case 6:
System.out.println(result + "Friday");
break;
case 7 :
System.out.println( result + "Saturday");
break;
default :
System.out.println ("Looks like that day doesn't exist");
break;
}
}
}
im using jdk se and i keep getting a parsing issue
"error: reached end of file while parsing"
i dont really understand why i keep getting this issue
i have my class closed and brackets in places i think i would need brackets.
import java.util.Scanner;
public class days_in_a_month {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a month:");
String month = input.nextLine();
input.nextLine();
System.out.print("Please enter a year:");
String year = input.nextLine();
input.nextLine();
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0)||(year % 400 == 0);
switch (month){
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":
System.out.println(month + " " + year + " has 31 days"); break;
case "4":
case "6":
case "9":
case "11":
System.out.println(month + " " + year + " has 30 days"); break;
case "2":
if(isLeapYear)
{
System.out.println(month + " " + year + " has 29 days"); break;
}
else
{
System.out.println(month + " " + year + " has 28 days");
}
}
}
the best way to solve is using some like this:
int year = input.nextInt();
In your code you are trying to use % operator with String
boolean isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
Operator % can't be used with String
just define year variable as int:
int year = Integer.valueOf(input.nextLine());
The problem is that you cannot use % operator for Strings
Here is the full example:
package com.yourpackage;
import java.util.Scanner;
public class days_in_a_month {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a month:");
String month = input.nextLine();
input.nextLine();
System.out.print("Please enter a year:");
int year = Integer.valueOf(input.nextLine());
input.nextLine();
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
switch (month) {
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":
System.out.println(month + " " + year + " has 31 days");
break;
case "4":
case "6":
case "9":
case "11":
System.out.println(month + " " + year + " has 30 days");
break;
case "2":
if (isLeapYear) {
System.out.println(month + " " + year + " has 29 days");
break;
} else {
System.out.println(month + " " + year + " has 28 days");
}
}
}
}
Don't forget to name your file for as "days_in_a_month" and to define the appopriate package in the top of the file!
The Best of The Best solve is:
package com.dayinmonth
import java.time.LocalDate;
import java.util.Scanner;
public class days_in_a_month {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a month:");
int month = input.nextInt();
input.nextLine();
System.out.print("Please enter a year:");
int year = input.nextInt();
input.nextLine();
LocalDate date = LocalDate.of(year, month, 1);
System.out.println(String.format("%d %d has %d days", date.getMonthValue(), date.getYear(), date.lengthOfMonth()));
}
}