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.
Related
Beginner here, please be as explanatory as possible!
A course question asked me to create a menu (done).
Have multiple option on the menu give different one-time result (done).
Now it wants me to implement a for, while and do...while loop (CANNOT UNDERSTAND)
I have genuinely tried all of my rudimentary knowledge, including creating and populating an array inside the for loop (which in hindsight was a stupid idea).
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit!");
System.out.println();
System.out.println("Please enter your choice:");
}
public void start()
{
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
public void startFor()
{
/*Each of these methods will modify the original start() method, each
*will add a loop of the specific type so that the menu is displayed
*repeatedly, until the last option is selected. When the last option
*is selected, exit the method (i.e. stop the loop).
*/
}
As you asked for an example with for in the comments.
The point of the exercise seems to be to iterate on the menu until an exit condition is met ("X".equals(input)). That means than between the three conditions in the for statement, that's the only one you need to specify. This is because the general form of a (basic) for statement is
for ( [ForInit] ; [Expression] ; [ForUpdate] )
Where none of those terms between brackets are mandatory, so we can as well get rid of [ForInit] and [ForUpdate] (but keeping the semicolons). This has the effect of not initializing anything with [ForInit] and doing nothing at the end of each iteration of the loop with [ForUpdate], leaving us only checking for the exit condition that is given by the [Expression] expression (when it's evaluated to false, the loop exits).
Notice that the console is declared outside the loop, since it would be wasteful to allocate one at each iteration. And also input, since you need it in the for statement's condition.
Scanner console = new Scanner(System.in);
String input = "";
for (;!"X".equals(input);) { // notice, the first and last part of the for loop are absent
displayMenu();
input = console.nextLine().toUpperCase();
System.out.println();
switch (input) {
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
You may notice this is a bit awkward, as this is not what you usually use a for loop for.
Anyway, at this point, the while version becomes trivial (while (!"X".equals(input))) and, in this case, the do...while is equivalent as well, (do { ... } while (!"X".equals(input))) as the same condition applies both at the end of the current loop and at the beginning of the next one, and there are no side effects between them.
As an aside, you may notice that while (condition) and for (; condition ;) are functionally equivalent and you may wander why you should use one instead of the other. The answer is readability. It's a lot more clear what you want to do when you do while (condition).
All arguments in for loop is not mandatory.
Define a stopflag and check whether is input is "X" or not.
Whenever input is "X" just change stopFlag or just simply you can break loop using break statement;
public void startFor()
{
boolean stopFlag = false;
for(; stopFlag == false ;) {
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
if(input.contentEquals("X"))
stopFlag = true;
}
}
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];
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
making a website in JSP on eclipse:
select[i] is acquired from the previous webpage correctly as a string from 1 to 5
each number represents a subject ie: if select[i]==1 so sub=Maths
I can not switch case on a string so I tried if else .. but sub is always equal to null (the declaration) ?? how can i make sub take the values in the if condition??
for (int i = 0; i < select.length; i++)
{
////
String sub=null;
if(select[i]=="1") {sub="Maths";}
else if (select[i]=="2") {sub="English";}
else if (select[i]=="3") {sub="Physics";}
else if (select[i]=="4") {sub="MI";}
else if (select[i]=="5") {sub="Software";}
////
rs=stmt.executeQuery("SELECT * FROM attends where userid= '"+user_id+"' and cid= '"+select[i]+"' ");
if(rs.next())//can not take it
{
out.println("You can not enroll in '"+sub+"' ");
}
else//can take it
{
int countUpdated =stmt.executeUpdate("INSERT INTO enroll (userid, cid) values ('"+user_id+"', '"+select[i]+"')");
out.println("Successfully enrolled in '"+sub+"' ");
}
}
This is one of the first problems I ever ran into while learning Java: the quandary of == vs equals. Fortunately, once you understand why they're different, it's easy to use them properly.
Whenever you're dealing with objects (as you are in this case), the == operator is used to determine whether two variables actually point to the same object. Objects are dealt with by reference in Java, so if object1 == object2, then the variable object1 actually refers to the same object that the variable object2 refers to.
This is not what you want here. You're trying to determine not whether two String variables point to the same object, but rather whether their contents are the same. For that, you should use the equals method, like so:
String sub=null;
if(select[i].equals("1")) {sub="Maths";}
else if (select[i].equals("2")) {sub="English";}
else if (select[i].equals("3")) {sub="Physics";}
else if (select[i].equals("4")) {sub="MI";}
else if (select[i].equals("5")) {sub="Software";}
This allows you to test whether the contents of sub are the same as the string "1", "2", etc.
And I believe your assumption about switch statements is incorrect: you can switch on a String in Java, and the equals method is used under the hood. So something like this:
String sub;
switch (select[i]) {
case "1":
sub = "Maths";
break;
case "2":
sub = "English";
break;
case "3":
sub = "Physics";
break;
case "4":
sub = "MI";
break;
case "5":
sub = "Software";
break;
default:
sub = null;
break;
}
might be preferable, because that's what switch statements are designed for.
Try this like
switch(select[i]) {
case "1":
sub="Maths";
break;
case "2":
sub="English";
break;
case "3":
sub="Physics";
break;
case "4":
sub="MI";
break;
case "5":
sub="Software";
break;
default:
sub="";
break
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I'm trying to work on my homework for class, and I'm using a switch case to make a command line interface, but I'm having a problem with the part I'm using. When I execute the addCard command, it goes through fine, but then afterwards goes to the default section. When I try using any of the other sections, or use it without the try segment, it works and doesn't go to default. Any thoughts on how to repair this? Code below
public static void cmdLine(String Cmd) {
switch(Cmd) {
case "Help":
case "?":
System.out.println("Available Commands:\naddCard = Add a card!\ndeleteCard = Delete a Card!\nfindCard = Locate Card Number by Name!\nCard (Card Number) = Work with your card");
break;
case "addCard" :
System.out.println ("Enter Account Name:");
String cName = scan.nextLine();
try {
System.out.println ("Enter Account Start Balance:");
int cBal = scan.nextInt();
System.out.println ("Enter Account Number:");
int cNum = scan.nextInt();
PPArray.addCard(cName, cBal,cNum);
} catch (InputMismatchException nfe) {
System.out.println("InputMismatchException: Please try again with only the card number. (Ex. 12345");
break;
}
break;
case "deleteCard" :
System.out.println("here we will have a command to remove the card from the array");
break;
case "Card" :
System.out.println("This will lead to a new function to operate with said card");
break;
case "Exit":
case "exit":
case "Quit":
case "quit":
return;
default :
System.out.println("Invalid Command ('?' or 'Help' for commands)");
System.out.println(PPArray.cardArray[1].name);
}
cmdLine(scan.nextLine());
}
When you run the try block in "addCard", you get input with int cNum = scan.nextInt();.
Then, when you call cmdLine(scan.nextLine()); after the switch statement, it consumes the new line, which causes the default clause to be called.
You can prevent this by adding scan.nextLine() at the end of that try block.
case "addCard" :
System.out.println ("Enter Account Name:");
String cName = scan.nextLine();
try {
System.out.println ("Enter Account Start Balance:");
int cBal = scan.nextInt();
System.out.println ("Enter Account Number:");
int cNum = scan.nextInt();
PPArray.addCard(cName, cBal,cNum);
scan.nextLine();
} catch (InputMismatchException nfe) {
System.out.println("InputMismatchException: Please try again with only the card number. (Ex. 12345");
break;
}
break;
BTW, I think it is bad coding to recursively call cmdLine(scan.nextLine()); in order to process the next input. I think a while loop would make more sense.
You have to actually exit the program if you want it to quit:
case "Exit":
case "exit":
case "Quit":
case "quit":
return;
should be
case "Exit":
case "exit":
case "Quit":
case "quit":
System.exit(0);
What is the next line?
cmdLine(scan.nextLine());
Is reading something that doesn't match any of the cases, your step debugger will show you where your logic error is. Step debugging is a much more valuable skill than System.out.println() and guessing.
change this
case "Exit":
case "exit":
case "Quit":
case "quit":
return;
to
case "Exit":
case "exit":
case "Quit":
case "quit":
break;
EDIT:
One more little issue is cmdLine(scan.nextLine()); taking new line each time and causing default to execute. Better to use cmdLine(scan.next()); which do not accept multiple words or line.
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);