How to match multiple input values in a switch case statement? - java

What piece of code do I need to make it so that if the user enters 7, 8, or 9 dogs; it will still output the message in case 6?
int dogs;
dogs = Integer.parseInt(JOptionPane.showInputDialog("How many dogs do you have?"));
switch (dogs)
{
...
...
...
case 4: JOptionPane.showMessageDialog(null,"Four dogs is too many."); break;
case 5: JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy person."); break;
case 6: JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
default: JOptionPane.showMessageDialog(null,"Invalid input.");
} // end switch

Check for an invalid number, then just use a default clause:
if (dogs < 0) {
JOptionPane.showMessageDialog(null,"Invalid input.");
} else {
switch(dogs) {
// ...
case 5:
JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy person.");
break;
default:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
break;
}
}

Simply add cases for 7,8,9 with 6
case 6:
case 7:
case 8:
case 9:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
break;

case 6:
case 7:
case 8:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
break;
This will do the job.
However I'd change it to:
case 4: JOptionPane.showMessageDialog(null,"Four dogs is too many."); break;
case 5: JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy person."); break;
default: JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");break;
This will eliminate the Invalid Output message, but will work for each and every number > 5, but i think that is acceptable, since the value of dogs comes out from an Integer.parseInt() call. If content is invalid an exceptin will be thrown there, and the Invalid Input message can be showed inside the exception handler and like wise an exception can be thrown if dogs is negative.
This has the advantage that will work for every number of dogs. If in need to manage a different error message, it will be enough just add the specific case branch.
int dogs;
try {
dogs = Integer.parseInt(JOptionPane.showInputDialog("How many dogs do you have?"));
if (dogs < 0) {
throw new Exception("Negative dog is impossible!");
}
switch (dogs)
{
...
...
...
case 4: JOptionPane.showMessageDialog(null,"Four dogs is too many."); break;
case 5: JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy person."); break;
default: JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");break;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Invalid input.");
}

import java.io.*;
import java.lang.*;
import java.util.*;
public class DogCheck {
public static void main(String[] args) {
int dogs;
Scanner input = new Scanner(System.in);
System.out.println("Enter Number of Dogs :");
dogs=input.nextInt();
if (dogs < 0)
System.out.println("WoW! Aliens has arrived...")
else
switch(dogs) {
case 4: JOptionPane.showMessageDialog(null,"Four dogs is too many."); break;
case 5: JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy `person."); break;`
default:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
break;
}
}
}

Related

Java switch statment, break statement unreachable

I am working on a program that is a simple game. I'm using a switch statement to return the file location of images that are assigned to buttons. In order to do this I am using a switch statement inside a method called "get Image View" it returns a string that can be fed into an image view that I will need to compare the image in the button to another image elsewhere. I think I may be over-explaining, anyway. my IDE (NetBeans) is telling me that my break statement is unreachable and I can not figure out why. I have used a switch statement that looks very similar to mine and there is an example in my textbook that is also very similar. I know that I still need to have a default return statement I just want to know what's up with my break statements. Thank you in advance!
public String getImageView(int button)
{
switch(button)
{
case 0: System.out.println("error");
case 1: return "1.png";
break;
case 2: return "2.png";
break;
case 3: return "3.png";
break;
case 4: return "4.png";
break;
case 5: return "5.png";
break;
case 6: return "6.png";
break;
case 7: return "7.png";
break;
case 8: return "8.png";
case 9: return "9.png";
case 10: return "10.png";
}
}
You can try something like below :
public String getImageView(int button){
String imageViewName = "";
switch(button)
{
case 0: System.out.println("error");
case 1: imageViewName = "1.png";
break;
case 2: imageViewName = "2.png";
break;
case 3: imageViewName = "3.png";
break;
case 4: imageViewName = "4.png";
break;
case 5: imageViewName = "5.png";
break;
case 6: imageViewName = "6.png";
break;
case 7: imageViewName = "7.png";
break;
case 8: imageViewName = "8.png";
break;
case 9: imageViewName = "9.png";
break;
case 10: imageViewName = "10.png";
break;
}
return imageViewName;
}
Hope this helps.
Well switch-state-statements behaves not like a big if-else-statement.
Consider this code:
int a = 0;
switch (a) {
case 0:
//do something
break;
case 1:
//do something else
break;
default:
//default case
}
Here the first case will be triggered as you can tell by the value of a.
If you want to first case be executed but also want to slip in the second case anyway you can omit the break in the first case.
So this code:
int a = 0;
switch (a) {
case 0:
System.out.println("case 0");
case 1:
System.out.println("case 1");
break;
default:
//default case
}
will output:
case 0
case 1
just like it is in your Code.
So maybe you should consider the break; in your first case. Otherwise it will execute the println but also returning 1.png.

Multiple args in a java switch

I am expecting my input to be one of three groups of chars and need to decide what to do with it based on which group it falls in. I'm trying to figure out how to define a switch with multiple cases to do this. Here is what I have so far:
while(in.hasNextChar())
{
char test = in.nextChar();
List<Signal> out = new List<Signal>(0);
switch(test)
{
case '1','0','x','X':
out.add(fromString(test));
break;
case ' ','/t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
}
return out;
}
You have the syntax wrong. You need to take advantage of fall-through:
switch(test) {
case '1':
case '0':
case 'x':
case 'X':
out.add(fromString(test));
break;
case ' ':
case '\t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
A case is just a label, very similar to what you'd use with a goto (which is essentially what is happening behind the scenes). It's not a statement, since it does nothing itself — it just names an address. So if test is '0', it can happily continue through the 'x' and 'X' cases to reach the actual statement code since there's not anything being done by those labels. Only break "ends" a case.
You can actually insert code between cases even without a break:
switch(test) {
case '1':
System.out.println("This is printed by case '1'");
case '0':
System.out.println("This is printed by both case '1' and case '0'");
break;
case 'x':
case 'X':
System.out.println("This is only printed by the Xs");
break;
default:
break;
}

Unable to get behaviour of Switch case in java

I have written small code in java 6
public class TestSwitch{
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:{
System.out.println(1);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
}
case 2:{
System.out.println(2);
case 5:
System.out.println(5);
case 7:
System.out.println(7);
}
}
System.out.println("end");
}
}
Output: start 1 2 end
My editor is showing orphaned case for 'case 3' and 'case 5'.Still it is running
and showing output.
Does Nastated cases like concept is there in Java?
And Why it is giving above output? rather i thought it will be 'start 1 end'
Your response will be greatly appreciated!!
Switch replaces if else's but switch syntax != If else syntax.
You forgot to put break after each case.
So conditions under fall through.
Example:
case 0:
mColor.setText("#000000");
break;
You can find that in docs
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
System.out.println(5);
break;
case 7:
System.out.println(7);
break;
default:
System.out.println("nothing");
}
switch(a){
case 1:{
System.out.println(1);
case 3:
You cannot nest cases like this. Switch should look either like :
switch(a){
case 1:
System.out.println(1);
break;
case 3:
....
or like this :
switch(a){
case 1:
System.out.println(1);
switch(a) {
case 3:
//...
break;
case 5 :
//...
And if you don't add break at the end of a case, the execution will continue after. You should add a break at the end of each cases if they should be executed separately.
You have wrong closing braces before case 2.
case 3,4 are interpreted as labels not cases.
Your code will give compilation errors as we can't use curly brace after case :
Exact code is:
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:
System.out.println(1);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
case 2:
System.out.println(2);
case 5:
System.out.println(5);
case 7:
System.out.println(7);
}
System.out.println("end");
}
}
and output will be start
1
3
4
2
5
7
end because you have not use "break" after each case.
As their no break statement in case 1: the execution directly jumps to case 2: and ends up printing "start 1 2 end"..
You have not added break statement before case 2.
Refer this to know more about fall through.
Each break statement terminates the enclosing switch statement. Control flow continues
with the first statement following the switch block. The break statements are necessary
because without them, statements in switch blocks fall through: All statements after
the matching case label are executed in sequence, regardless of the expression of
subsequent case labels, until a break statement is encountered.
int a = 1;
System.out.println("start");
switch (a) {
case 1: {
System.out.println(1);
break;
}
case 3: {
System.out.println(3);
break;
}
case 4: {
System.out.println(4);
break;
}
case 2: {
System.out.println(2);
break;
}
case 5: {
System.out.println(5);
//no break will fall through and print 7 too
}
case 7: {
System.out.println(7);
break;
}
default:{
System.out.println("none");
}
}
See if a=1 then your case 1 will work then 1 will pe printed if as we have not using break after case 1 so all cases are working in flow so output is coming like this if you want to execute only one case at one time then you have to put break after one case like
switch(a){
case 1:
System.out.println(1);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
Then it will break out of the switch case on encountering break statement

Output to a single dialog box depending on user input

When I compile I get an error message saying 'message' hasn't been initialized. What I'm trying to accomplish is instead of having multiple JOptionPane.showMessageDialog statements, I just want one statement in my code that will output any of the messages listed below depending on the user input.
int dogs;
String message;
dogs = Integer.parseInt(JOptionPane.showInputDialog("How many dogs do you have?"));
if (dogs >= 6)
{
message = "That is totally unbelieveable.";
}
else
{
switch (dogs)
{
case 0: message = "You really should get a dog. They're great pets."; break;
case 1: message = "Glad you have a dog."; break;
case 2: message = "Two dogs are better than one."; break;
case 3: message = "Three dogs is a lot."; break;
case 4: message = "Four dogs is too many."; break;
case 5: message = "Five dogs means you're a crazy person."; break;
JOptionPane.showMessageDialog(null,message);
default: JOptionPane.showMessageDialog(null,"Invalid input."); break;
} // end switch
} // end if
Try initializing the string when declaring it.
String message = "";
OR
String message = null;
If dogs >= 6 it won't be outputted either. You need to move your message outside the if/else block.
if (dogs >= 6)
{
message = "That is totally unbelieveable.";
}
else
{
switch (dogs)
{
case 0: message = "You really should get a dog. They're great pets."; break;
case 1: message = "Glad you have a dog."; break;
case 2: message = "Two dogs are better than one."; break;
case 3: message = "Three dogs is a lot."; break;
case 4: message = "Four dogs is too many."; break;
case 5: message = "Five dogs means you're a crazy person."; break;
default: message = "Invalid input."; break;
} // end switch
} // end if
JOptionPane.showMessageDialog(null,message);

How can I make this better

Ok here I have a switch case statement which is falling through and trying every option. Basically I want something that if the user enters the letter A in the textbox the background will change to b! if they dont enter the letter A then I want it to stop executing the code. But what has been happening is if the user enters lets say for example the letter Q when the background is letter A then the background will change to letter R instead of telling the user that they are wrong. basically I would like to know how I can stop the background from changing if the user does not enter the letter they are on here is the code.
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
switch(ch - 'A') {
case 0:
//A;
gestureViewer.setBackgroundResource(R.drawable.lettersb);
break;
case 1:
gestureViewer.setBackgroundResource(R.drawable.lettersc);
break;
case 2:
gestureViewer.setBackgroundResource(R.drawable.lettersd);
break;
case 3:
gestureViewer.setBackgroundResource(R.drawable.letterse);
break;
case 4:
gestureViewer.setBackgroundResource(R.drawable.lettersf);
break;
case 5:
gestureViewer.setBackgroundResource(R.drawable.lettersg);
break;
case 6:
gestureViewer.setBackgroundResource(R.drawable.lettersh);
break;
case 7:
gestureViewer.setBackgroundResource(R.drawable.lettersi);
break;
case 8:
gestureViewer.setBackgroundResource(R.drawable.lettersj);
break;
case 9:
gestureViewer.setBackgroundResource(R.drawable.lettersk);
break;
case 10:
gestureViewer.setBackgroundResource(R.drawable.lettersl);
break;
case 11:
gestureViewer.setBackgroundResource(R.drawable.lettersm);
break;
case 12:
gestureViewer.setBackgroundResource(R.drawable.lettersn);
break;
case 13:
gestureViewer.setBackgroundResource(R.drawable.letterso);
break;
case 14:
gestureViewer.setBackgroundResource(R.drawable.lettersp);
break;
case 15:
gestureViewer.setBackgroundResource(R.drawable.lettersq);
break;
case 16:
gestureViewer.setBackgroundResource(R.drawable.lettersr);
break;
case 17:
gestureViewer.setBackgroundResource(R.drawable.letterss);
break;
case 19:
gestureViewer.setBackgroundResource(R.drawable.letterst);
break;
case 20:
gestureViewer.setBackgroundResource(R.drawable.lettersu);
break;
case 21:
gestureViewer.setBackgroundResource(R.drawable.lettersv);
break;
case 22:
gestureViewer.setBackgroundResource(R.drawable.lettersw);
break;
case 23:
gestureViewer.setBackgroundResource(R.drawable.lettersx);
break;
case 24:
gestureViewer.setBackgroundResource(R.drawable.lettersy);
break;
case 25:
gestureViewer.setBackgroundResource(R.drawable.lettersz);
break;
would it be better if I set the pictures in an array and then went from there? Ive tried including If switch case, but it didnt work at all....
I'd pre-populae an array and invoke:
gestureViewer.setBackgroundResource(myArray[ch - 'A']);
It will make your code much more readable.
You can also do it with a Map<Character,MyImage> - it might allow you to add more features easily in the future.
If you do that, invokation will be using
gestureViewer.setBackgroundResource(myMap.get(ch));
Note that the array/map needs to be populated only once in the application's runtime.
You could, for example, put all the R.drawable.abc inside an Array and then address its index.
int[] bgImg = {R.drawable.a, ... , R.drawable.z}
char ch = words.getText().toString().toUpperCase().charAt(0);
int index = ch - 'A';
if(index > 0 && index < bgImg.length){
gestureViewer.setBackgroundResource(bgImg[index]);
} else {
gestureViewer.setBackgroundResource(R.drawable.standardImage);
}
Also note, that I'm using toUpperCase() to make sure you can substract the capital 'A'
Try:
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
int id = getResources().getIdentifier("letters" + ch, "drawable", context.getPackageName())
gestureViewer.setBackgroundResource(id);
}
}

Categories