Switch integer to string - java

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

Related

How to use strings as the same as inputting int?

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.

Java - Method program - using switch case with method

I'm writing a program that takes in the users birth information, year, month, day, hour, minute. The program is the following:
Use the getRangedInt method to input the year (1965-2000), month
(1-12), Day*, hours (1 – 24), Minutes (1-59) of a person’s birth.
Note: use a switch() conditional selector structure to limit the user
to the correct number of days for the month they were born in. For
instance if they were born in Feb [1-29], Oct [1-31]. HINT: there are
only a few groups here not 12 different ones!
I'm absolutely confused with the day part. I have managed to get everything else to work except understand what I'm supposed to do for the day.
My code:
public static void main(String[] args)
{
int year, month, day, hour, minutes;
String msg="";
boolean done = true;
Scanner in = new Scanner(System.in);
while(done)
{
year = SafeInput.getIntInRange(in, "Enter the year you were born: ", 1965, 2000);
month = SafeInput.getIntInRange(in, "Enter your month of birth: ", 1, 12);
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", day, day);
hour = SafeInput.getIntInRange(in, "Enter the hour you were born in: ", 1, 24);
minutes = SafeInput.getIntInRange(in, "Enter the minutes you were born: ", 1, 59);
System.out.println("You were born: " + year + " , " + msg + " , " + hour + " hr. " + minutes + " mins. ");
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
}
}
The getIntInRange just does a basic input to get the number in range.
I'm confused because I don't know how to do the range for the day since there is also supposed to be a switch used.
This is a very strange requirement.
It looks like what is requested from you looks like something like this:
int numberOfDays;
switch (month) {
case 1: // $FALL-THROUGH
case 3: // $FALL-THROUGH
case 5: // $FALL-THROUGH
case 7: // $FALL-THROUGH
case 9: // $FALL-THROUGH
case 11:
numberOfDays = 31;
break;
case 4: // $FALL-THROUGH
case 6: // $FALL-THROUGH
case 8: // $FALL-THROUGH
case 10: // $FALL-THROUGH
case 12:
numberOfDays = 30;
break;
case 2:
numberOfDays = (0 == year / 4) ? 29 : 28;
break;
default:
throw new IllegalArgumentException("month not 1-12");
} // switch (too long for my liking)
and then
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, numberOfDays);
This utilizes a fall-through construct available in switches, so if you meet a condition, you are going to execute until a return statement (or break/throw).
Please remember that the alternative is to have something like:
private static final Set<Integer> MONTHS_30_DAYS = Sets.newTreeSet(4, 6, 8, 10, 12);
private static final Set<Integer> MONTHS_31_DAYS = Sets.newTreeSet(1, 3, 5, 7, 9, 11);
public static int numberOfDays(int month, int year) {
if (MONTHS_30_DAYS.contains(month)) {
return 30;
} else if (MONTHS_31_DAYS.contains(month)) {
return 31;
} else {
return (0 == year / 4) ? 29 : 28;
}
}
Here your day is dependent on the month entered. So firstly you'd want to take the month entered by the user as an Integer like you're doing now and proceed to use that number in a switch:
int month = 0;
int numberOfDays;
switch (month) {
case 1: numberOfDays = DaysInJanuary;
break;
case 2: numberOfDays = DaysInFebruary;
break;
case 3: numberOfDays = DaysInMarch;
break;
case 4: numberOfDays = DaysInApril;
break;
case 5: numberOfDays = DaysInMay;
break;
case 6: numberOfDays = DaysInJune;
break;
case 7: numberOfDays = DaysInJuly;
break;
case 8: numberOfDays = DaysInAugust;
break;
case 9: numberOfDays = DaysInSeptember;
break;
case 10: numberOfDays = DaysInOctober;
break;
case 11: numberOfDays = DaysInNovember;
break;
case 12: numberOfDays = DaysInDecember;
break;
default: throw new IllegalArgumentException("Not a valid month");
break;
}
You can then proceed to set your variable for the max day range.
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, numberOfDays);
Hope this helped.
Your day range depends on the previous month number the user entered, so you have to check that in order to know which day range to display. What the hint tells you is that you don't need a different range of valid days for each month because some months share the same range. Here are the number of days in a month:
January 31
February 28/29
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
As you can see, there are only 3 groups and the assignment wants you to utilize fallthrough - when you don't break in a switch:
int upperDaysLimit;
switch(month) {
case 1:
case 3:
case 5:
//...
case 12: upperDaysLimit = 31;
break;
case 4:
case 6:
// and so on
}
and now you can use that range limit on your days inquiry:
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, upperDaysLimit);
If you're required to use switch statement, you can split months by the number of days in them. There will be 3 groups. Than you can use a switch statement as follows:
switch (month) {
case 1:
case 3:
case 5:
return 31;
case 2: {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
return 29;
else
return 28;
}
case 4:
case 6:
return 30;
default:
throw new IllegalArgumentException("some error text");
}
The switch statement in the example is not full, you should write a case statements for every month. Basically you're returning the upper value for day.

Output not printing after switch case utilized Java

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

Using Enumerations to find Day of Week

My code asks for the user to enter the day with an integer value ie Sunday = 0, Monday = 1, etc., then asks the user to input a number representing an offset day. From there the program finds the day corresponding to the offset number ie
Enter today's day: 0 //Sunday
Enter the number of days elapsed since today: 6
6 days from Sunday is Sunday
The problem with the above output is that since I'm using, "%6" to find the offset day, it skips one day for values 6.
Also, I can't figure a way to find the day for an entered negative offset value. ie
Enter today's day: 0 //Sunday
Enter the number of days elapsed since today: -2
-2 days from Sunday is Friday
Here's my code
import java.util.Scanner ;
public class test {
public static void main (String[] args) {
Scanner Input = new Scanner(System.in);
System.out.print("Enter today's day: ");
int today = Input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int offset = Input.nextInt ();
int offsetDay = 0;
if (offset >= 0)
offsetDay = (today + offset)% 6 ; //to get remainder and make it vary from 0 - 6
else if (offset < 0)
offsetDay = (today - offset)% 6 ;
String todayText = null ;
String offsetText = null;
//Converting input integers into days in text for variable today
switch (today) {
case 0 : todayText = "Sunday" ; break;
case 1 : todayText = "Monday"; break;
case 2 : todayText = "Tuesday"; break;
case 3 : todayText = "Wednesday";break;
case 4 : todayText = "Thrusday"; break;
case 5 : todayText = "Friday"; break;
case 6 : todayText = "Saturday"; break;
}
//Converting input integers into days in text for variable offset
switch (offsetDay) {
case 0 : offsetText = "Sunday" ; break;
case 1 : offsetText = "Monday"; break;
case 2 : offsetText = "Tuesday"; break;
case 3 : offsetText = "Wednesday";break;
case 4 : offsetText = "Thrusday"; break;
case 5 : offsetText = "Friday"; break;
case 6 : offsetText = "Saturday"; break;
}
System.out.println(offset + " days from " + todayText + " is " + offsetText);
}
}
My last question is, how would I implement this using enumeration? Any thoughts?
Please, try this code snippet, maybe this will help you:
public class Days
{
enum DAY
{
MON("Monday"),
TUE("Tuesday"),
WED("Wednesday"),
THU("Thursday"),
FRI("Friday"),
SAT("Saturday"),
SUN("Sunday");
private String name;
private DAY(String name)
{
this.name= name;
}
#Override
public String toString()
{
return this.name;
}
public DAY add(int days)
{
int posMod = (this.ordinal() + days) % values().length;
if (posMod < 0)
{
posMod += values().length;
}
return DAY.values()[posMod];
}
}
public static void main(String[] args)
{
DAY a = DAY.values()[0];
System.out.println(a);
System.out.println(a.add(-2));
System.out.println(a.add(0));
System.out.println(a.add(-8));
}
}
You should use %7 instead of %6 as counting from 0-6 inclusive is 7.

My Switch statement is not working as expected

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.

Categories

Resources