Switch statements using || & && [duplicate] - java

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 ?

Related

Multiple if condition in java " if value exists in a list " [duplicate]

I have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.)
Instead of writing something like:
if (x == 12 || x == 16 || x == 19 || ...)
is there any way to format it like
if x is [12, 16, 19]?
Just wondering if there is an easier way to code this, any help appreciated.
The answers have been very helpful, but I was asked to add more detail by a few people, so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this:
if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))
I was just wondering if there was a faster way to code things like that - many of the answers below have helped.
I use this kind of pattern often. It's very compact:
// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));
// In your method:
if (values.contains(x)) {
...
}
A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.
If performance is not important, you can code the gist of it into one line:
if (Arrays.asList(12, 16, 19).contains(x))
but know that it will create a new ArrayList every time it executes.
Do you want to switch to this??
switch(x) {
case 12:
case 16:
case 19:
//Do something
break;
default:
//Do nothing or something else..
break;
}
If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like
if (x == 12 || x == 16 || x == 19 || ...)
else if (x==34 || x == 55 || ...)
else if (...)
Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become
switch(dispatchTable[x])
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
}
Whether or not this is appropriate depends on the semantics of the problem.
If an array isn't appropriate, you could use a Map<Integer,Integer>, or if you just want to test membership for a single statement, a Set<Integer> would do. That's a lot of firepower for a simple if statement, however, so without more context it's kind of hard to guide you in the right direction.
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
You could look for the presence of a map key or see if it's in a set.
Depending on what you're actually doing, though, you might be trying to solve the problem wrong :)
No you cannot do that in Java. you can however write a method as follows:
boolean isContains(int i, int ... numbers) {
// code to check if i is one of the numbers
for (int n : numbers) {
if (i == n) return true;
}
return false;
}
With Java 8, you could use a primitive stream:
if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))
but this may have a slight overhead (or not), depending on the number of comparisons.
Here is another answer based on a comment above, but simpler:
List numbers= Arrays.asList(1,2,3,4,5);
if(numbers.contains(x)){
//
}

Java Date class- switches and ifs in the constructor

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!

JAVA Intellij Coding

String marital = (String) JOptionPane.showInputDialog("Are you a single or married joint filer?");
while ((marital.length() >= 6) && (marital.length() <= 7)) {
System.out.println("You are " + marital + " thank you.");
if (marital.length() > 7) {
break;
}
}
im pretty new to Java so i was wondering how i could stop the while loop from printing more than one line. The objective is that the user will say single or married but i dont know how to only print it once
Just put break; after print, just like that, no if or anything. Right now you have your break inside if, that checks condition that will for sure fail, because if there was a possiblity that marital.length > 7 then it wouldn't even enter this while loop, since you are making sure that it's length is 7 or lower. All this code is weird tho, you are probably doing all this to train/learn, but I suggest just doing this:
String marital = (String) JOptionPane.showInputDialog("Are you a single or married joint filer?");
if ((marital.length() == 6) || (marital.length() == 7)) {
System.ou.tprintln("You are " + marital + " thank you.");
}
That will check if martital length is 6 OR 7 (you had something like that in your code, expressed in a convoluted way) and if yes then it's gonna print your sentence.

Multi-Condition Ifs [duplicate]

I have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.)
Instead of writing something like:
if (x == 12 || x == 16 || x == 19 || ...)
is there any way to format it like
if x is [12, 16, 19]?
Just wondering if there is an easier way to code this, any help appreciated.
The answers have been very helpful, but I was asked to add more detail by a few people, so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this:
if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))
I was just wondering if there was a faster way to code things like that - many of the answers below have helped.
I use this kind of pattern often. It's very compact:
Define a constant in your class:
private static final Set<Integer> VALUES = Set.of(12, 16, 19);
// Pre Java 9 use: VALUES = new HashSet<Integer>(Arrays.asList(12, 16, 19));
In your method:
if (VALUES.contains(x)) {
...
}
Set.of() returns a HashSet, which performs very well even for very large sets.
If performance is not important, you can code the gist of it into one line for less code footprint:
if (Set.of(12, 16, 19).contains(x))
but know that it will create a new Set every time it executes.
Do you want to switch to this??
switch(x) {
case 12:
case 16:
case 19:
//Do something
break;
default:
//Do nothing or something else..
break;
}
If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like
if (x == 12 || x == 16 || x == 19 || ...)
else if (x==34 || x == 55 || ...)
else if (...)
Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become
switch(dispatchTable[x])
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
}
Whether or not this is appropriate depends on the semantics of the problem.
If an array isn't appropriate, you could use a Map<Integer,Integer>, or if you just want to test membership for a single statement, a Set<Integer> would do. That's a lot of firepower for a simple if statement, however, so without more context it's kind of hard to guide you in the right direction.
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
You could look for the presence of a map key or see if it's in a set.
Depending on what you're actually doing, though, you might be trying to solve the problem wrong :)
No you cannot do that in Java. you can however write a method as follows:
boolean isContains(int i, int ... numbers) {
// code to check if i is one of the numbers
for (int n : numbers) {
if (i == n) return true;
}
return false;
}
With Java 8, you could use a primitive stream:
if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))
but this may have a slight overhead (or not), depending on the number of comparisons.
Here is another answer based on a comment above, but simpler:
List numbers= Arrays.asList(1,2,3,4,5);
if(numbers.contains(x)){
//
}

Java Question: Is it possible to have a switch statement within another one?

I have a yes or no question & answer. I would like to ask another yes or no question if yes was the answer. My instructor wants us to use charAt(0) as input for the answer.
Is it possible to have a switch statement within another one (like a nested if statement)?
EDIT: Here is a sample of my pseudo code =
display "Would you like to add a link (y = yes or n = no)? "
input addLink
switch (link)
case 'y':
display "Would you like to pay 3 months in advance " + "(y = yes or n = no)?"
input advancePay
switch(advPay)
case 'y':
linkCost = 0.10 * (3 * 14.95)
case 'n'
linkCost = 14.95
case 'n'
linkCost = 0.00
Yes, but don't. If you need a further level of logic like that, place the second Switch in its own method with a descriptive name.
EDIT: By the example you've added, you've got two Boolean conditions. I would recommend against using switch at all, using if & else conditionals instead. Use (STRING.charAt(0) == 'y') as your test case, or something methodical like boolean isY(final String STRING) { return (STRING.charAt(0) == 'y' || STRING.charAt(0) == 'Y'); }
Yes. Switches break the language block statement pattern, but this is mainly because of C/C++ from which the switch statement used by Java is based.
In all three languages, the switch statement takes the following form:
switch(variable) {
case n:
statement 1;
statement n;
(optional) break;
case n+1:
statement 1;
statement n;
(optional) break;
// Optionally more statements
(optional) default:
statement 1;
statement n;
}
Because a switch statement breaks the traditional language pattern, many programmers wrap their multiple statements in a case using the traditional block style: { }
This is because most constructs in all three languages allow block style statements to be considered as one statement, but the switch statement does not require block style to execute multiple statements in a single case.
Without the break statement separating each case, there will be "fall through" - if case n was matched and did not have a break, the code under it (case n + 1) would be executed - if case n + 1 did not have a break and was matched, the default code would execute, if neither had a break, when matching case n, the code for case n, case n+1 and default would be executed.
The default is optional, and specifies a default action for a switch statement to execute. Typically, the default condition is either a generic handler, or a good place to throw an exception if the value could not logically be any other than the values in the switch statement.
To illustrate a switch statement executing inside a switch statement, take a look at this contrived example:
String message = null;
int outerVariable = getOuterVariable();
switch(outerVariable) {
case n:
statement 1;
statement n;
break;
case n+1:
int innerVariable = getInnerVariable();
switch(innerVariable) {
case 1:
message = "IT WAS 1";
break;
default:
message = "WHY WOULD YOU DO THIS? OH THE HUMANITY!";
}
break;
// Optionally more statements
(optional) default:
statement 1;
statement n;
}
It is possible, but that would be very convoluted and hard to read. There's almost certainly a better way, such as calling a method within the first switch statement and doing any more necessary processing (including another switch if necessary) in that method.
Most programming languages are orthogonal. That means, using a feature usually does not depend on the location, if meaningful.
For example, you cannot declare a local variable as public.

Categories

Resources