Output to a single dialog box depending on user input - java

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

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.

Invoking ignore case in switch statements

In the below code containing the switch statements, is it possible to incorporate the equalsIgnoreCase method, i.e., user gets grade message whether or not a or A is entered, etc. etc.?
I managed to get the right result by using "convert user input to upper case" method, but I was curious whether the ignoreCase method can be used here. I tried to do it, but it does not seem to work in any way, possibly because ignoreCase is a Boolean which returns true/false result, not a message. I tried researching this, but all online results suggest using toUpperCase method, something I already tried and worked.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter grade.");
String gradeLetter = scan.next();
String message = "A";
switch (gradeLetter) {
case "A":
message = "Excellent!";
break;
case "B":
message = "Good job.";
break;
case "C":
message = "You passed.";
break;
case "D":
message = "You can do better.";
break;
case "F":
message = "You failed.";
break;
default: message = gradeLetter + " is invalid.";
}
System.out.println(message);
You could switch (gradeLetter.toUpperCase()) but this looks like a better use case for Map<String, String> to me. Something like
Scanner scan = new Scanner(System.in);
Map<String, String> map = new HashMap<>();
map.put("A", "Excellent!");
map.put("B", "Good job.");
map.put("C", "You passed");
map.put("D", "You can do better.");
map.put("F", "You failed.");
// ... No Loop?
System.out.println("Please enter grade.");
String gradeLetter = scan.next();
System.out.println(map.getOrDefault(gradeLetter.toUpperCase(),
String.format("%s is invalid.", gradeLetter)));
As you already mentioned, you can switch on gradeLetter.toUpperCase().
You can also use fall-through, where multiple case labels jump to the same block of code:
switch (gradeLetter) {
case "A":
case "a":
message = "Excellent!";
break;
case "B":
case "b":
message = "Good job.";
break;
/* etc */
Consider, for example, "a" and "A". There is no break statement after case "A":, so execution continues straight into the case "a": block.

switch with while loop won't end when told to

I have two methods, getOption() and driver().
getOption() takes a String from a scanner, breaks it into individual words, and returns an array of Strings.
driver() then gets the first value of that array, getOption()[0], and begins a while loop based on that first String. While the String does not equal "quit", check if the value matches any switch case. However, when I run it, it can do any of the switch cases, but the quit statement never works. Can anyone give me a hand?
public String[] getOption(){
String optionLine[];
Scanner input = new Scanner(System.in);
System.out.println("Input string\n");
String line = input.nextLine();
optionLine = line.split(" ");
return optionLine;
}
public void driver(){
String option = getOption()[0];
Stats s = new Stats(data);
while (!"quit".equals(option)){
switch (option) {
case "add": //data.put(getOption()[1], getValues());
System.out.println("add");
break;
case "set": System.out.println("set");
break;
case "print": System.out.println(Arrays.toString(data));
break;
case "sum": System.out.println(s.sum());
break;
case "mean": System.out.println(s.mean());
break;
case "stdev": System.out.println(s.standardDeviation());
break;
case "median": System.out.println(s.median());
break;
case "primes": System.out.println(s.primes());
break;
case "summary": System.out.println("summary");
break;
//case "test": System.out.println(Arrays.toString(getValues()));
}
driver();
}
}
You are calling recursively at the end of your while loop the method driver();
no matter if you read getOption or not, you are still coming back inside the method...
that is the reason of the apparently not working while condition...
a very unusual pitfall.
Once you get into your While loop, you never change the value of option. You could change your while to be
while (true){
option = getOption()[0];
Stats s = new Stats(data);
switch (option) {
case "add": //data.put(getOption()[1], getValues());
System.out.println("add");
break;
case "set": System.out.println("set");
break;
case "print": System.out.println(Arrays.toString(data));
break;
case "sum": System.out.println(s.sum());
break;
case "mean": System.out.println(s.mean());
break;
case "stdev": System.out.println(s.standardDeviation());
break;
case "median": System.out.println(s.median());
break;
case "primes": System.out.println(s.primes());
break;
case "summary": System.out.println("summary");
break;
//case "test": System.out.println(Arrays.toString(getValues()));
case "quit": break;
}
}
Note, if you use my answer, you will need to no longer recursively call driver().
You don't seem to be changing the value of option anywhere. You're calling driver() recursively, but that doesn't affect the local variable in the currently executing method which stays the same.
So, one driver() method calls another, which creates its own option variable, unrelated to the option variable of the caller. Basically, only the innermost call to driver() will ever return and you'll be stuck in the while loop of its caller.
Get rid of that recursion, it's unnecessary. Under the switch just call getOption() and update the value of option.
while (!"quit".equals(option)){
// switch statement
option = getOption()[0];
}

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

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

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

Categories