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)
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
Java. There is an online store, classes of products, constructors, etc. (I have all I need) There is also an array of products.
The switch statement provides a choice, the user need to select the number of product on the console. I want the user to be able to select several products (not only one product), so I added scanners (I hope there is nothing bad in scanner) I have a method which directs user to the main menu, is called in this code as firstMethod ();
The problem with the transition to the main menu through the switch statement. When I press 1, 3 and so on - the products are displayed, but when I press 6 then firstMethod (the method that calls the main menu in this online store) really work, but not "in time". When I press 1, the 1 case is executed, the program is waiting for my input of the next number. I press 6 (to go to main menu) and for some reason the program displays case 2. Then I press 6 and console displays case 3, and so on. Two more times and the console displays the main menu, this is really what I want to be shown right that moment when I press number 6.
Tell me please - what is wrong with that? How to go to the main menu (call the method) with this operator, or is it better to use another one? Write it please.
So I want firstMethod to work when user press 6 number. Can I do this via switch or I need another operator? Please help I will be really gratefull.
public static void switch1() {
Product[] products = {
new Fridge(),
new Fridge(),
new Fridge(),
...
...
...
};
Scanner scan = new Scanner(System.in);
System.out.println("1 - " + products[0]);
System.out.println("2 - " + products[1]);
System.out.println("3 - " + products[2]);
System.out.println("4 - " + products[3]);
System.out.println("5 - " + products[4]);
System.out.println("6 - Go to main menu");
System.out.println("Which one do u want to buy?");
int i = Scanner.nextInt();
switch (i) {
case 1:
System.out.println(products[0]);
Scanner.nextInt();
case 2:
System.out.println(products[1]);
Scanner.nextInt();
case 3:
System.out.println(products[2]);
Scanner.nextInt();
case 4:
System.out.println(products[3]);
Scanner.nextInt();
case 5:
System.out.println(products[4]);
Scanner.nextInt();
case 6:
firstMethod();
}
It seems like the only visible problem is that there are no break; statements at the end of each of your case blocks.
For example:
switch (i) {
case 1:
System.out.println(products[0]);
Scanner.nextInt();
break;
...
Also, just calling Scanner.nextInt(); won’t do anything unless you use the value returned by the call.
You also said you wanted the user to be able to select multiple products, so in order to do that, you could put the switch in a loop, such as a while loop, and have it loop until a condition is met to stop it.
Edit: The following code shows a small example of what your code structure could be:
boolean loop = true;
while (loop) {
int i = scan.nextInt();
switch (i) {
case 1:
System.out.println(product[0]);
break;
//... cases 2-5 are similar to case 1
case 6:
firstMethod();
loop = false;
break;
}
}
This can be done in a much more efficient manner without a switch at all.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < products.length; i++) {
System.out.println((i + 1) + " - " + products[i]);
}
System.out.println((products.length + 1) + " - Go to main menu");
System.out.println("Which one do u want to buy?");
while (true) {
int selection = Scanner.nextInt();
if (selection > 0 && selection <= products.length) {
System.out.println(products[selection - 1]);
} else {
break;
}
}
firstMethod();
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");
}
This question already has answers here:
Java switch statement multiple cases
(15 answers)
Closed 8 years ago.
I am trying to get my head around switch statements. I understand how to use a switch statement using a single variable but I cannot workout how to make the following code segment work:
If they cannot be done like this ( I struggled to find any info in google) could you please suggest a more effective way that would work if I wanted to add more cases which is why I am reluctant to use if statements.)
Edit: I'm not sure that my question was understood properly. I was wondering if it is possible to use the "And" and "OR" operators in a switch statement to make a switch statement that checks that two different variables match the requirements of each case. E.G Boy and girl are over 10, girl or boy are over 10, etc...
I was asking for a Switch statement Solution specifically as this is more of a tutorial program than a useful program.
Also its really annoying getting my question marked down as being a duplicate when none of the so called "answers" that already exist answer my question and the many many unhelpful comments that ignore my question really suck.
enter code here
public class AgeCheck {
public static void main(String args[]){
int boy, girl;
boy = 21;
girl = 22;
switch(boy & girl){
case 1: boy > 10 && girl > 10;
break;
System.out.println("You can enter...");
case 2: boy || girl < 10;
System.out.println("You cannot enter, someone amongst you is unworthy...");
break;
default:
System.out.println("Your age is unknown...");
}
}
}
You can't use boolean operators with switch statements. What you can do is something like this:
case 1: case 2:
// do some stuff
break;
You need not to have switch here and the way you wrote is not correct usage of switch.
You need a proper if else
if (boy > 10 && girl > 10) {
System.out.println("You can enter...");
} else if (boy < 10 || girl < 10) {
System.out.println("You cannot enter, s...");
} else {
System.out.println("Your age is unknown...");
}
Clear. Right ?
This is for an assignment for a computers class. This is going beyond what the teacher asked for, so I am not asking you people to do my school work for me. What I am not able to understand is how to exit the switch and the while. I know that using break; will exit the while loop, and using break; will exit a switch. What I am looking for is some code that will exit a switch and a while loop at the same time. What I could do is just use
if (upgrade == 1){
// Do Stuff
}
if (upgrade == 2){
// Do Stuff
}
if (upgrade == 3){
// Do Stuff
}
if (upgrade == 4){
// Do Stuff
}
if (upgrade == 0){
break; // Exit the while loop
}
However, the teacher does not want us to use that format, but instead use switches. I also thought that I could just add the
if (upgrade == 0){
Break;
}
To the bottom, but that still is not using a switch, and my teacher would not be happy with it. Is there any way to exit a swtich and a while loop at the same time?
This is what he wants the code to look like:
while (timesLeveled > 0){
System.out.println("Upgrade Stats");
upgrade = chooseUpgrade(); // retrieves the number for upgrade
switch (upgrade){
case 1:
// Do stuff if upgrade is 1
break;
case 2:
// Do stuff if upgrade is 2
break;
case 3:
// Do stuff if upgrade is 3
break;
case 4:
// Do stuff if upgrade is 4
break;
case 0:
break;
} // Closes off Switch
timesLeveled--; // resets level counter
} // Closes off while (timesLeveled)
I would usually recommend against using a switch at all when you have the option, but if you have to stick with it, you probably want the break with label.
WhileLoop: while (timesLeveled > 0) {
...
case n:
// do stuff
break WhileLoop;
...
}
Note that this usage usually means that your code needs more than one significant cleanup (Replace Conditional with Polymorphism, loop improvement, etc.).