Right not I'm trying to use switch() to validate the user input.
The scenario here is I am validating data corresponding to the calendar year.
I'm trying to validate that if you enter a month that contains 30 days (April, June, September, November), but enter a day value of 31, that it returns an error message.
I'm not going to lie. This is for an assignment, and I am in no way wanting ANYONE to just give me the answer, but if you can maybe explain what I am doing wrong.
Any help is great help. Here's the syntax for the two switch()es I have tried.
switch(monthInput)
First attempt:
case 1:
if((monthInput = 4 )&& (dayInput > 30))
{
System.out.printf("%n%d%s", dayInput, ERROR_MESSAGE[3]);
}
else if((monthInput = 6)&& (dayInput > 30))
{
System.out.printf("%n%d%s", dayInput, ERROR_MESSAGE[3]);
}
else if((monthInpt = 9)&& (dayInput > 30))
{
System.out.printf("%n%d%s", dayInput, ERROR_MESSAGE[3]);
{
else if((monthInput = 11) && (dayInput > 30))
{
System.out.printf("%n%d%s", dayInput, ERROR_MESSAGE[3]);
}
Second Attempt:
switch(monthInput)
{
case 1:
if((monthInput = 4 | monthInput = 6 | monthInput = 9 | monthInput = 11) && (dayInput < 30))
{
System.out.print("The day you entered is invalid for the month you specified
}
}
You can continue to use switch statements if you like. If you are switching on month then it would look something like:
switch(monthInput) {
case 2: // feb
if (dayInput > (leapYear ? 29 : 28))
...
break;
case 4: // apr
case 6: // jun
case 9: // sep
case 11: // nov
if (dayInput > 30)
...
break;
case 1: // jan
case 3: // mar
case 5: // may
case 7: // jul
case 8: // aug
case 10: // oct
case 12: // dec
if (dayInput > 31)
...
break;
default:
// error
}
If you have already learnt about arrays you might try having an array containing the number of days in each month and then comparing to the appropriate value using the month as index. Alternatively, you could use an enum of the months which would look something like:
public enum Month {
JAN(31), FEB(28), MAR(31), APR(30), ....;
private final int days;
Month(int days) {
this.days = days;
}
public int getDays(boolean leapYear) {
if (this == FEB && leapYear)
return days + 1;
else
return days;
}
}
Getting the days in a particular month would be Month.values()[monthInput].getDays(leapYear)
The pathway a switch takes is determined by the controlling statement (in this case, monthInput). When you write case 1 you're telling the switch what statements to execute when the value of monthInput is 1 (in other words, if the statements for case 1 are being executed then we already know that monthInput = 1). So in this case, I'm not sure a switch is your best option as far as validation goes because it doesn't make sense to try to validate monthInput if you already know the value.
Also, as previously pointed out to check equivalence you use == not =, and || for the or operator.
Apart from the obvious syntax error (==, ||), the more important problem is you don't understand what switch is.
Read your book again for the section of switch, when you see
switch (A) {
case X:
XXX;
case Y:
YYY;
}
It should read: I am going to switch the logic based on value of A. case X: means, if A equals X, logic underneath will be executed.
In your case, you do something similar to:
switch(month) {
case 1:
if (month == 4 || month ==6) {
...
}
...
}
the line case 1: means, if month is 1, but underneath it, you check if month equals to 4 or 6, which will never happen and not making any sense.
Please understand the tool before you try to use it. Using it by blind guessing is not going to work.
In Java, = is used for assigning a value and == is used for testing equality.
Also OR uses || not |
so try
if((monthInput == 4 || monthInput == 6 || monthInput == 9 ||
monthInput == 11) && (dayInput < 30))
{
System.out.print("The day you entered is invalid for the month you specified");
}
Related
int month = input.nextInt();
switch (month) {
case 1:
System.out.println(“January”);
case 2:
System.out.println(“February”); break;
case 3:
System.out.println(“March”); break;
case 4:
System.out.println(“April”);
case 5:
System.out.println(“May”); break;
default:
System.out.println(“Invalid”); break;
}
How do I convert it from switch statement into if-else statment?
the breaks are intentional, this is a college assignment.
In pseudo code, you could check all connected parts, without a break statement, together in a single statement and check the values in another nested if statement.
if 1 or 2
if 1 print january
print february
else if 3 print march
else if 4 or 5
if 4 print april
print may
else print invalid
int month = input.nextInt();
if(month==1){
System.out.println(“January”);
System.out.println(“February”);
}else if(month==2){
System.out.println(“February”);
}
you should be able to repeat that for the next cases. Please try to clean up your code next time, if we are giving time to answer you should at least put in time to ask properly, thanks
I want to create a Java Program that takes a date as input (27,2,2019) and print out what day it was. I am just assuming the usage of Gregorian Calender only. The reference is 1,1,1 which is a Monday. I am unable to complete this. Can someone help me out please. I also took leap years to account. Also, in this project, I am not allowed to import any packages so I should do it normally.
public class sortday
{
public static void main (String [] args)
{
sortdayoftheyear(1,1,2019);
}
public static void sortdayoftheyear(int day, int month, int year)
{
final int [] months = {31,28,31,30,31,30,31,31,30,31,30,31};
{
final int monthnum = 12;
int totaldays=0;
int newmon = month-1; //find which month it is
int monthdays = months[newmon]; // find days of the month
for (int i = 1; i < year; i++)
{
if (i%100 != 0 && i%4 == 0 && i%400 == 0) //check for leap year
{
totaldays = i*366;
}
else
totaldays = i*365;
}
totaldays += (day) + (newmon*monthdays);
if (totaldays%7 == 4)
System.out.println("Sunday");
if (totaldays%7 == 5)
System.out.println("Monday");
if (totaldays%7 == 6)
System.out.println("Tuesday");
if (totaldays%7 == 0)
System.out.println("Wednesday");
if (totaldays%7 == 1)
System.out.println("Thursday");
if (totaldays%7 == 2)
System.out.println("Friday");
if (totaldays%7 == 3)
System.out.println("Saturday");
System.out.println("It had been " + totaldays + " since January 1,AD");
}
}
}
There seems to be more than one bug in your code. I have spotted:
Each time through your for loop you are assigning a new value to totaldays. In this way only the last time through the loop has any effect in the end. I believe you intended every iteration to contribute.
As yole said in a comment, newmon*monthdays is incorrect for the total number of days in the first newmon months of the year. I even think that for February 13 your are counting 13 + 1 * 28, which can’t be right. One suggestion is you loop through the months and add up their lengths.
If the entered year is a leap year, you are always counting 28 days in February. You want to count 29 sometimes. An auxiliary method to determine whether a year is a leap year would come in handy.
If your reference date of January 1, 1 is a Monday, I think you want to print this when the modulo operation in the end yields 1. You are printing Thursday in this case.
I can’t tell if there may be more.
Issues without functional consequences that you should nevertheless want to fix include:
You are not using the constant monthnum, so delete it.
You have a superfluous set of braces around the code piece from the mentioned constant down to System.out.println. Delete those too.
Get your indentation right so you and I can read your code.
When writing code for others to read (including Stack Overflow users), respect the naming conventions. Call the class SortDay or FindDayOfWeek. The method sortDayOfTheYear or printDayOfWeek.
I'm a beginner i have an assignment to write a Date class (as part of a bigger project).
in my question i focus on the constructor. here's some background:
the given guidelines are that the date is not expected to be valid and the following instance variables expect this input range:
day- integer 1-31
month- integer 1-12
year- integer 4 digits year.
now, if an invalid day/month/year or invalid date (such as 31.2.2010) is entered, the object will be created with the date of 1.1.2000.
this is the code I've come up with and it does compile and seem to work fine.
public class Date
{
private int _day;
private int _month;
private int _year;
public Date (int day, int month, int year)
{
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: if ((day>0 && day<32) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
case 4:
case 6:
case 9:
case 11: if ((day>0 && day<31) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
case 2: if (leap(year))
{
if ((day>0 && day<30) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
}
else
{
if ((day>0 && day<29) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
}
}
}
/** check if leap year */
private boolean leap (int y)
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
}
here are my questions:
is it fine to put all that code in the constructor? will it greatly affect the processing time or cause an error? is there an alternative if its a problem?
is any part of the code could be considered a bad practice? such as the switches and ifs?
I'm not feeling to confident with this build despite it working fine...
is it fine to put all that code in the constructor? will it greatly affect the processing time or cause an error? is there an alternative if its a problem?
Well, there's nothing wrong with the code in your constructor body. As long as your syntax is correct, your code will always run fine. However, one important thing you need to know is this: When the complexity of the code in the body of your constructor reaches a certain level, it starts to tell on your processing time. A good illustration is a situation where you have multiple loops and/or heavy background processes in your constructor. This is the reason why putting heavy processes in a constructor body is frowned upon (but not prohibited).
is any part of the code could be considered a bad practice?
There are a number of ways you can optimize your code:
You can give your global and instance variables the same name and distinguish between them using the this keyword.. i.e: this.day = day;
Take advantage of already-available classes and packages in Java. The Calendar class has methods that return the number of days in a month and so on. Instead of reinventing the wheel, use them. Check this question to see how to get the number of days in a month. There are bunch of other methods that may be useful to you too.
Lastly, You can declare a separate method to set the value to your chosen default state (01-01-2000) so that you won't have to be setting it every time, this would largely reduce your lines of code.
I hope this helps.. Merry coding!
Sorry I'm a beginner so the answer may be obvious but I'm trying to make a code where it will tell you your horoscope based on your dob and based off that tell you your daily, monthly, and yearly horoscope.
import java.io.*;
public class MysticLady {
static String zodiacSign = "";
static String dailyDescript = "";
private static java.util.Scanner myScanner;
public static void main(String[] args) throws Exception
{
BufferedReader keyIn = new BufferedReader (new InputStreamReader(System.in));
Thread.sleep(1000);
System.out.println("Welcome user to the world of the mystic truths!");
Thread.sleep(3000);
System.out.println("My name is Mirela and will be telling you all about you...");
Thread.sleep(3000);
System.out.println("But first, what is your name?");
myScanner = new java.util.Scanner(System.in);
String name = myScanner.nextLine();
Thread.sleep(1000);
System.out.println( name + ", what a lovely name");
Thread.sleep(3000);
System.out.println("Well " + name + ", I need to first know your date of birth");
Thread.sleep(3000);
System.out.println("Keep in mind that by knowing this I will be able to tell you certain things");
Thread.sleep(3000);
System.out.println("We currently have daily, monthly, and yearly horoscopes available");
Thread.sleep(3000);
System.out.println("Now first tell me what month were you born (1-12)");
int month = Integer.parseInt(keyIn.readLine());
System.out.println("Now what day were you born?");
int day = Integer.parseInt(keyIn.readLine());
Thread.sleep(1000);
System.out.println(name + ", the galaxy is telling me that your zodiac sign is " + MysticHoroscope1.getZodiacSign());
System.out.println("Now that we know your sign, would you like to know your daily, monthyly, or yearly horoscope?");
String horotype = myScanner.nextLine();
{
if (horotype.equalsIgnoreCase("daily"))
{
Thread.sleep(1000);
System.out.println("Today is May 11, 2017");
System.out.println("Your horoscope for today is...");
System.out.println("" + MysticHoroscope1.getDailyDescript());
if (horotype.equalsIgnoreCase("monthly"))
{System.out.println("");
if (horotype.equalsIgnoreCase("yearly"))
{System.out.println("");
}
}}}}}
public class MysticHoroscope1 {
private static String zodiacSign;
int month;
int day;
public MysticHoroscope1(int m, int d)
{
int month = m;
int day = d;
switch (month)
{
case 1 :
if (day > 0 && day <= 20)
setZodiacSign("Capricorn");
else if (day > 20 && day < 32)
setZodiacSign("Aquarius");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 2 :
if (day > 0 && day <= 19)
setZodiacSign("Aquarius");
else if (day > 19 && day < 30)
setZodiacSign("Pisces");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 3 :
if (day > 0 && day <= 20)
setZodiacSign("Pisces");
else if (day > 20 && day < 32)
setZodiacSign("Aries");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 4 :
if (day > 0 && day <= 20)
setZodiacSign("Aries");
else if (day > 20 && day < 31)
setZodiacSign("Taurus");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 5 :
if (day > 0 && day <= 21)
setZodiacSign("Taurus");
else if (day > 21 && day < 32)
setZodiacSign("Gemini");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 6 :
if (day > 0 && day <= 21)
setZodiacSign("Gemini");
else if (day > 21 && day < 31)
setZodiacSign("cancer");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 7 :
if (day > 0 && day <= 22)
setZodiacSign("Cancer");
else if (day > 22 && day < 32)
setZodiacSign("Leo");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 8 :
if (day > 0 && day <= 21)
setZodiacSign("Leo");
else if (day > 21 && day < 32)
setZodiacSign("Virgo");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 9 :
if (day > 0 && day <= 23)
setZodiacSign("Virgo");
else if (day > 23 && day < 31)
setZodiacSign("Libra");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 10 :
if (day > 0 && day <= 23)
setZodiacSign("Libra");
else if (day > 23 && day < 32)
setZodiacSign("Scorpio");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 11 :
if (day > 0 && day <= 22)
setZodiacSign("Scorpio");
else if (day > 22 && day < 31)
setZodiacSign("Sagittarius");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 12 :
if (day > 0 && day <= 22)
setZodiacSign("Sagittarius");
else if (day > 22 && day < 32)
setZodiacSign("Capricorn");
else
setZodiacSign("Sorry, that's not a valid date");
break;
default :
setZodiacSign("Sorry, that's not a valid date");
}
}
public void MysticHoroscope(int month2, int day2) {
}
public static String getZodiacSign() {
return zodiacSign;
}
public static void setZodiacSign(String zodiacSign) {
MysticHoroscope1.zodiacSign = zodiacSign;
}
public static String dailyDescript;
{
if (zodiacSign.equals("Capricorn"))
setDailyDescript("There are many ways to journey through life,\nbut you will only know the path you choose to travel.\nThis is a wonderful day to expose yourself to new art,\nespecially if it's from a different culture.\nTurn the dial on your radio or television to a foreign-language broadcast.\nLeave it there for a few minutes. You'll be surprised how intriguing you find it.\nEvery now and then, it's wise to travel down an unfamiliar side street.");
if (zodiacSign.equals("Aquarius"));
setDailyDescript("Stand up for yourself and watch how quickly people back down.\nToday, you will be able to talk to absolutely anyone--even the folks who usually intimidate you.\nIt's a great day to ask for a raise, try to get some face time with the big boss, or ask someone out on a date.\nYou'll give off an unmistakable air of confidence, which might be a bit stronger than what you actually feel.\nThis level of boldness could open up some very important doors for you.");
if (zodiacSign.equals("Pisces"));
setDailyDescript("Finding a balance between what you want and what is best for everyone involved is important today.\nBefore making any decisions, you have to factor in other people's feelings and goals.\nThis could be difficult, because you can't exactly read minds.\nLuckily, your intuition is strong, and you can sense what people want.\nDon't bend too far backward to accommodate them, though.\nJust let them know you considered their feelings -- that's plenty of incentive.");
}
public static String getDailyDescript() {
return dailyDescript;
}
private static void setDailyDescript(String dailyDescript) {
MysticHoroscope1.dailyDescript = dailyDescript;
}
}
Everything "works" except for the actual answer.
name, the galaxy is telling me that your zodiac sign is null
Now that we know your sign, would you like to know your daily, monthyly, or yearly horoscope?
daily
Today is May 11, 2017
Your horoscope for today is...
null
Issues include:
You're setting the class variable dailyDescript in an instance initializer. You want an instance member. Remove static from the declaration.
That initializer gets called before setZodiacSign() is called, and then never again. You'll want to either move that code so that it can be called after setZodiacSign(), or initialize the zodiac sign and description in the constructor.
When you move that code to allow calling it from setZodiacSign(), you'll need to cover all the zodiac signs in that code, and ideally, provide a final else that handles bad values in some way.
You have global variables in the class containing main() that are neither necessary nor used.
I try to modify your code as little as possible for the answer (even if everything in my body strive against it).
Your class MysticLady
You have:
Thread.sleep(1000);
System.out.println(name + ", the galaxy is telling me that your zodiac sign is " + MysticHoroscope1.getZodiacSign());
Problem:
The class MysticHoroscope1 contains the logic for the horoscopy in the constructor, but that one is never called.
Solution. Just add one line in between:
Thread.sleep(1000);
new MysticHoroscope1(month, day);
System.out.println(name + ", the galaxy is telling me that your zodiac sign is " + MysticHoroscope1.getZodiacSign());
The class MysticHoroscope1 contains
Next class MysticHoroscope1
You have:
public static void setZodiacSign(String zodiacSign) {
MysticHoroscope1.zodiacSign = zodiacSign;
}
public static String dailyDescript;
{
if (zodiacSign.equals("Capricorn"))
setDailyDescript("There are many ways to journey through life,\nbut you will only know the path you choose to travel.\nThis is a wonderful day to expose yourself to new art,\nespecially if it's from a different culture.\nTurn the dial on your radio or television to a foreign-language broadcast.\nLeave it there for a few minutes. You'll be surprised how intriguing you find it.\nEvery now and then, it's wise to travel down an unfamiliar side street.");
if (zodiacSign.equals("Aquarius"));
setDailyDescript("Stand up for yourself and watch how quickly people back down.\nToday, you will be able to talk to absolutely anyone--even the folks who usually intimidate you.\nIt's a great day to ask for a raise, try to get some face time with the big boss, or ask someone out on a date.\nYou'll give off an unmistakable air of confidence, which might be a bit stronger than what you actually feel.\nThis level of boldness could open up some very important doors for you.");
if (zodiacSign.equals("Pisces"));
setDailyDescript("Finding a balance between what you want and what is best for everyone involved is important today.\nBefore making any decisions, you have to factor in other people's feelings and goals.\nThis could be difficult, because you can't exactly read minds.\nLuckily, your intuition is strong, and you can sense what people want.\nDon't bend too far backward to accommodate them, though.\nJust let them know you considered their feelings -- that's plenty of incentive.");
}
Problems:
The description for the horoscope is initialized in an anonymous block when the class is instantiated and depends on the zodiacSign. But the zodiacSign is initialized in the constructor (actually after the anonymous block is evaluated)
The if-statements ends with colons
Solution. Make this:
public static void setZodiacSign(String zodiacSign) {
MysticHoroscope1.zodiacSign = zodiacSign;
if (zodiacSign.equals("Capricorn"))
setDailyDescript("There are many ways to journey through life,\nbut you will only know the path you choose to travel.\nThis is a wonderful day to expose yourself to new art,\nespecially if it's from a different culture.\nTurn the dial on your radio or television to a foreign-language broadcast.\nLeave it there for a few minutes. You'll be surprised how intriguing you find it.\nEvery now and then, it's wise to travel down an unfamiliar side street.");
if (zodiacSign.equals("Aquarius"))
setDailyDescript("Stand up for yourself and watch how quickly people back down.\nToday, you will be able to talk to absolutely anyone--even the folks who usually intimidate you.\nIt's a great day to ask for a raise, try to get some face time with the big boss, or ask someone out on a date.\nYou'll give off an unmistakable air of confidence, which might be a bit stronger than what you actually feel.\nThis level of boldness could open up some very important doors for you.");
if (zodiacSign.equals("Pisces"))
setDailyDescript("Finding a balance between what you want and what is best for everyone involved is important today.\nBefore making any decisions, you have to factor in other people's feelings and goals.\nThis could be difficult, because you can't exactly read minds.\nLuckily, your intuition is strong, and you can sense what people want.\nDon't bend too far backward to accommodate them, though.\nJust let them know you considered their feelings -- that's plenty of incentive.");
}
public static String dailyDescript;
I strongly encourage you to rethink your design.
zodiacSign is holding the value of null in your program, so that's what it is printing. I would suggest you to check for null to eliminate that issue.
Your null check should look like this:Previously it was the same only not commented
if (zodiacSign!=null && !zodiacSign.isEmpty) {
//do your stuff here...
} else {
//what you want to do if get null zodiacSign
}
this is not an issue, but i suggest trying to format your code for better readability as it is staggered.
Hi I am programming a calculator with the 5 choices of operations.
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
I want to ask the user to make a choice of the operation and check whether the choice valid (i.e. 1 - 5) If not, give a wrong message and prompt the user to select again.
I am thinking using if-else statement with switch statement within the else statement.
System.out.printf("What would you like to do? ");
int selection = input.nextInt();
if (selection!=1 || 2 || 3 || 4 || 5) {
System.out.println("You have entered an invalid choice, please re-enter
your choice: ");
}/*end if as long as the selection is NOT a 1 - 5, prompt the user to
re-enter*/
else {
switch(selection){
case 1:
case 2:
case 3:
case 4:
case 5;
I am getting an Eclipse compiler error at the if line:
The operator || is undefined for the argument type(s) boolean, int
Any ideas what is wrong and how to fix this? Thanks
Kelvin
You don't even need that if statement
switch(selection){
case 1:
// handle 1
break;
case 2:
// handle 2
break;
case 3:
// handle 3
break;
case 4:
// handle 4
break;
case 5:
// handle 5
break;
default:
System.out.println("You have entered an invalid choice, please re-enter
your choice: ");
break;
}
The default clause will handle every statement that doesn't fit in any of the cases.
The if statement needs valid expressions between the conditional operators. Perhaps
if (selection != 1 && selection != 2 && selection != 3
&& selection != 4 && selection != 5) {
...
}
You cannot combine conditional cases like that in Java like we would in English. "If the selection is not 1 or 2 or 3 or 4 or 5" cannot be translated to Java that way. You must explicitly state selection each time, or else the compiler will think you are attempting to use the || operator on selection != 1, a boolean, and 2, an int, hence the error. Additionally, the value is always "not 1" or "not 2" or ... You should use "and" (&&).
if (selection!=1 && selection!=2 && selection!=3 && selection!=4 && selection!=5) {
This can be simplified because the numbers are consecutive:
if (selection < 1 || selection > 5)