Whenever I put .toLowerCase or .toUpperCase it doesn't work for me. It shows me the error constant string expression required. I was wondering if anyone could help me figure out how to fix this. Here's some code to help you out.
static final String SCISSORS = "Scissors".toUpperCase();
switch (choice) {
case SCISSORS:
System.out.println("I choose scissors");
break;
case PAPER:
System.out.println("I choose paper");
break;
case ROCK:
System.out.println("I chose rock");
break;
}
You must surround each value with " characters to use switch with Strings
The choice and SCISSORS fields are not related. You must fix that by changing the declaration. This is a possible solution:
final String choice = "Scissors".toUpperCase();
switch (choice) {
case "SCISSORS": System.out.println("I choose scissors"); break;
case "PAPER": System.out.println("I choose paper"); break;
case "ROCK": System.out.println("I chose rock"); break;
}
There's little point in using .toUpperCase on a string that literally appears in your source code, when it's easy enough to write the upper case form yourself.
The trick is to make the various fixed values into compile-time constants, as I have done in the following quick example. Then you can use the values in 'case' clauses in a switch statement.
I intentionally used single-character names for the constants to make it clear whether we were talking about the name or the value.
It is of course necessary (or at least user-friendly) to convert the user input to upper case as well, prior to the comparison.
I'm a lazy typist so I did not bother to declare a 'choice' variable, I just read the required value directly in the switch statement. I didn't prompt either. Don't do this at home.
import java.util.Scanner;
public class S {
final static String S = "SCISSORS";
final static String R = "ROCK";
final static String P = "PAPER";
public static void main(String... args) {
switch (new Scanner(System.in).next().toUpperCase()) {
case S: System.out.println("Scissors"); break;
case R: System.out.println("Rock"); break;
case P: System.out.println("Paper"); break;
}
}
}
Related
Im new in programming, so this is kind of basic but I cant find an answer here on why is this keep happenning. "The operator || is undefined for the argument type(s) char, char",can someone please help, its for our task. Thanks in advance.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char choice = (scan.next().charAt(0));
switch (choice) {
case ('A'||'a'):
System.out.println("Wrong Answer");
break;
}
}
}
You can't logically OR together characters in Java. The closest thing to what you want to do in Java might be:
switch (choice) {
case 'A':
case 'a':
System.out.println("Wrong Answer");
break;
}
Here we are letting both cases of A to flow to the same case. Another option:
switch (Character.toUpperCase(choice)) {
case 'A':
System.out.println("Wrong Answer");
break;
}
This approach first uppercases the input character, and then we only need to check uppercase letters in the switch statement.
You could replace switch with regular if statement and use || operator:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char choice = scan.next().charAt(0);
if (choice == 'A' || choice == 'a') {
System.out.println("Wrong Answer");
}
}
}
However, much better will be operating with String class. And next() from Scanner returns exactly String instance. With small modification it could be like:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String firstLetter = scan.next().substring(0, 1);
if (StringUtils.equalsIgnoreCase(firstLetter, "A")) {
System.out.println("Wrong Answer");
}
}
}
Also, used equalsIgnoreCase() from StringUtils class. You have to add this dependency to the project with your build manager.
You can convert character to the lower or upper case:
switch (Character.toLowerCase(choice)) {
case 'a': System.out.println("Wrong Answer"); break;
}
As other answers have said, you can have only one value in each case statement. Other answers have suggested using two case statements. However, recent versions of Java (since version 13) have an enhanced switch statement which makes it much neater:
switch (choice) {
case 'A', 'a' -> System.out.println("Wrong Answer");
}
See how much neater it is? Not only do you not need two case statements, but you don't need a break statement either.
Other answers have suggested using Character.toLowerCase, but there are problems with that. Consider this:
switch (Character.toLowerCase(choice)) {
case 'i':
System.out.println("Correct answer");
break;
default:
System.out.println("Wrong answer");
break;
}
The problem is Character.toLowerCase is sensitive to the current locale. If a user in Turkey runs the above, and types I, they'll get "Wrong answer" instead of correct answer. This is because in Turkish, the lowercase equivalent of the letter I is not i, but ı (an i without a dot). Similar problems occur with toUpperCase and in some other languages. I wouldn't recommend using toLowerCase/toUpperCase for this reason.
I have my code written in if/else Statement and it is working but I have a problem in writing it using switch statement as it appears that there are problems in my variables and symbols.
Can you please spot what is wrong and help me correct it?
My source code below.
import java.util.Scanner;
import java.io.*;
public class CourseCodeSWITCH {
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case A: code = "Accounting";
break;
case B: code = "Banking and Finance";
break;
case C: code = "Computer Science";
break;
case D: code = "Dentistry";
break;
case E: code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
}
}
You're using A, B, C, as labels, but that's not how a switch statement works. Let's take a look at just one statement:
switch (code) {
case A: code = "Accounting";
break;
You're switching on code... this means you're going to be examining the contents of the code variable.
Next, you declare a case. In the case above, you're effectively saying
if (code == A)
code = "Accounting";
break;
Now, there's a couple things wrong with that. First of all, A is not defined anywhere, so you're immediately going to run into compile-time errors. You probably wanted to use a String value ("A") instead. Second, you're just reassigning code instead of outputting like you did in your original if-statement.
You probably want a switch that looks closer to the following:
switch(code) {
case "A":
System.out.println("Assignment");
break;
case "B":
System.out.println("Banking and Finance");
break;
// and so forth
}
In Java 7/8 you can define the String to compare code to. In earlier versions you may want to use a char or enum.
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case "A":
code = "Accounting";
break;
case "B":
code = "Banking and Finance";
break;
case "C":
code = "Computer Science";
break;
case "D":
code = "Dentistry";
break;
case "E":
code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
Additionally here is an example from Oracle.
Just starting Java so it's probably a simple question but couldn't find any questions like mine so figured I would post one.
I am writing a "main menu" with options 1-8. I figured out how to error handle when someone types a number larger than 8 and less than 1 but I can't figure out how to give them an error message if they type a character or letter...
while(menuChoice != 8)
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
}
Assuming this compiles, what you're asking would be impossible. You're switching on a number, so you can't check if the number is a character. Your code wouldn't compile if that were possible.
You should take the user input as a String and validate the String. If the String has non-numeric values in it, then throw an error. If it doesn't, convert it to a number then execute your switch.
A better design would be to have a validation layer. Once the input is validated, just assume it's valid thereafter.
Pseudocode:
String input = //
if (containsNonNumerics(input))
throw error
inputAsInt = castToInt(input)
if (outOfRange(inputAsInt)
throw error
switch //your current code goes here
First off, having that while loop is not going to give you the functionality that you want. You should look into how to use KeyAdapter in order to be able to receive input events from the keyboad, e.g. a number being pressed, and then you can validate that it is actually a number, and if it is you can then use your switch statement to determine the proper code to execute.
I am guessing that menuChoice is a character. In which case, you can either do a manual check that
if('0' <= mc && mc <= '9') {
// do your regular checks
}
If it is a string then do a
try {
Integer.parseInt(mc)
} catch (NumberFormatException e) { // Not a number. Do your error reporting stuff }
HTH.
Switch statment work only with numeric types (int, byte, char, short). If you try add in switch anything else the compailer wouldent allowe you in general. But if you somehow (cating or other way) want to add in switch statment varible you must befor check it with if statment if the varible is type that you want.
Example:
if(var instanceof String){
System.out.println("Error we don't acceped type string");
}
else{
switch(var){
....
}
}
Use this function before entering into while loop and display the error message.
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
int menuChoice ;
//Now get input from customer in menuChoice
//Your logic goes herr... example menuChoice = ..whateverinput
//After the input is captured then validate
if(menuChoice <1 || menuChoice >8 )
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
else {
System.out.println("Please Enter Valid Entry");
}
In the 1 month experience I've had with any programming language, I've assumed that switch case conditions would accept anything in the parenthesis as a boolean checking thingamajig, ie
these:
|| && < >
Know what I mean?
something like
char someChar = 'w';
switch (someChar) {
case ('W' ||'w'):
System.out.println ("W or w");
}
Sadly, doesn't seem to work that way. I can't have boolean checking in switch case.
Is there a way around it?
By the way, terribly sorry if I'm sounding confusing. I don't quite know the names for everything in this language yet :X
Any answers appreciated
You can achieve an OR for cases like this:
switch (someChsr) {
case 'w':
case 'W':
// some code for 'w' or 'W'
break;
case 'x': // etc
}
Cases are like a "goto" and multiple gotos can share the same line to start execution.
You can do -
switch(c) {
case 'W':
case 'w': //your code which will satisfy both cases
break;
// ....
}
Every case is normally followed by a "break;" statement to indicate where execution should terminate. If you omit the "break;", then execution will continue. You can use this to support multiple cases which should be handled the same way:
char someChar = 'w';
{
case 'W':
// no break here
case 'w':
System.out.println ("W or w");
break;
}
Switch cases are branches for alternative evaluations of a given expression. The expression is given in the switch parenthesis and can be byte, short, char, and int data types.
The body of a switch statement is known as a switch block. A statement
in the switch block can be labeled with one or more case or default
labels. The switch statement evaluates its expression, then executes
all statements that follow the matching case label.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
For an alternate to switch statement(multiple if conditions), I think the best solution will be using an enum. For example: Consider the case below:-
public enum EnumExample {
OPTION1{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the first option.");
return void;
}
},
OPTION2{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the second option.");
return void;
}
},
OPTION3{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the third option.");
return void;
};
public static final String CLASS_NAME = Indicator.class.getName();
public abstract void execute();
}
The above enum can be used in the following fashion:
EnumExample.OPTION1.execute();
Hopefully this helps you guys.
I am attempting to use a Switch statement to use as a menu interface, and I was wondering how I can include a "help" option, which is triggered by the user having input a '?' symbol.
But as the Switch is accepting type 'char', I am not sure how this is possible.
Could you please point me in the right direction?
Here is my non-compiling code so far:
private char readChoice()
{ System.out.print("Choice (a/b/c/s/?/x): ");
return In.nextLine().toLowerCase().charAt(0); }
private void execute(char choice)
{ switch (choice)
{ case 'a': routes.show(); break;
case 'b': customers.book(routes); break;
case 'c': customers.show(); break;
case 's': routes.showSchedule(); break;
case '\?': showHelp(); break;
case 'x': break; }}
private String showHelp()
{ String helpText = " A/a Show bookings by route\n";
helpText += " B/b Book a trip\n";
helpText += " C/c Show bookings by customer\n";
helpText += " ? Show choices\n";
helpText += " X/x Exit\n";
return helpText; }
One other question, is there a more suitable way to implement the 'Exit' option, rather than just having a break after an 'x' is input?
Thank you for taking the time to read through my question.
There's nothing special about the question mark character within the Java language. You don't need to escape it - it's not like in a regular expression. Just use:
case '?': showHelp(); break;
See JLS section 3.10.4 for the characters you do need to escape (and the escape sequences available).
EDIT: As per the comments, the problem is with the showHelp() method, which builds a string but doesn't return it. You probably want something like:
private String showHelp() {
out.println(" A/a Show bookings by route");
out.println(" B/b Book a trip");
out.println(" C/c Show bookings by customer");
out.println(" ? Show choices");
out.println(" X/x Exit");
}
... for a suitable value of out.
(As an aside, your bracing style is odd and I for one find it pretty hard to read. There are two common bracing styles in Java - the one I showed in the above code, and the "brace on a separate line at the same indentation as the closing brace" version. For the sake of others who might read your code, it's probably worth adopting one of those common styles.)
There is no need to escape the ? in a char:
case '?': showHelp(); break;
is there a more suitable way to implement the 'Exit' option, rather than just having a break after an 'x' is input?
It if fine but it would work the same way if you removed it. What would possibly make more sense would be something like:
case 'x': break;
default: showErrorMessage();
So if the user enters an unauthorised character, you let him know.
You do not need to escape the '?' in a char. Also - you're not doing anything with the String you construct and return from showHelp() currently. You would need to do something with that like:
String message;
switch(choice) {
//.. stuff ommitted
case '?': message = showHelp(); break;
Or you should display the message within showHelp.