Multiple characters in a switch statement? - java

just to clarify this is hw.
In a project we're doing, a user isn't allowed to enter numbers or special characters (i.e ! # £ etc)
char letter;
String phonetic;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter: ");
letter = letter = kb.next().charAt(0);
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
case '1,2,3,4,5,6,7,8,9,0':
{
System.out.println('No number input please!');
}
break;
}
The error is on
'1,2,3,4,5,6,7,8,9,0'
Eclipse says
invalid character constant
Isn't it really long winded if I have to enter all the numbers manually?
i.e. case '1': case '2':
even with
case 1,2,3,4,5,6,7,8,9,0:
It won't work.
Is there an shorter way to do this using switch statements?
Thank you!

Its because Case expression should be an int-compatible literal or a String from java 7.
case '1,2,3,4,5,6,7,8,9,0':
character literals are represented using single quotes. c, it should only be of one length, while your case doesn't reflect that, thus the error.
'1,2,3,4,5,6,7,8,9,0' this is not a legal character.
If you just wanna check if the character is only alpha, then use Charcter#isDigit(char) or Charcter#isLetter before the switch starts like in below code:
char ch= (Character.toUpperCase(letter);
if(!Character.isDigit(ch)) {
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
}
}
else {
System.out.println("no numbers please")
}

There's no easier way using case, what about?:
if ('0' <= letter && letter <= '9')
System.out.println('No number input please!');

Isn't it really long winded if I have to enter all the numbers manually?
Yes.
Is there an shorter way to do this using switch statements?
No.
Consider an if statement instead...

No, Java in this situation is not smart like C#. You need to write multiple lines for that. If you want to compare strings you need to use if statements. Also remember to use this code for comparision:
if("search".equals(string2)) {...}
You cannot compare by == this would only compare the memory addresses. Also note that I use the equals on the static string and not on the variable string2 because you code would break if string2 is null.

I hope this one enlighten you more.
Consider, your expression generates output as A , B, C, D, E, F, G, H, I, ...till Z. and you want to execute same method/function for all them.
Then, you can check the ascii values of the characters and modify your code to use if and for loop or else use switch as mentioned in the program in following example program.
Play around with code to learn more.
public class SwitchClass
{
public void method1()
{
System.out.println("Menthod 1");
}
public void method2()
{
System.out.println("Menthod 2");
}
public void method3()
{
System.out.println("Menthod 3");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
SwitchClass sw = new SwitchClass();
System.out.println("Enter the String:");
String input = in.next();
for(int i = 0; i<input.length(); i++)
{
switch(Character.toUpperCase(input.charAt(i)))
{
case 'A':
case 'B':
case 'C':
case 'U':
System.out.println(Character.toUppercase(input.charAt(i))+" Case calling");
sw.method1();
sw.method2();
sw.method3();
break;
default:
System.out.println("No number input please!");
break;
}
}
}
}

Related

Control Flow Condition

I fail to understand why For loop keeps executing, if condition meet and break statement applied.
Code:
class ProgramControlStatements {
public static void main(String[] args) throws java.io.IOException {
System.out.println("Menu: ");
System.out.println("Choice: ");
System.out.println("1: If/Else");
System.out.println("2: Switch");
for(int i = 0; i < 5; i++) {
chooseOption();
};
};
static void chooseOption() throws java.io.IOException{
char choice = (char) System.in.read();
switch(choice){
case 'a':
System.out.println("Computer control statement: If/Else");
break;
case 'b':
System.out.println("Computer control statement: Switch");
break;
default:
System.out.println("No valid option");
};
}
}
Expected result:
If char a chosen, print "If/Else" and expect next input until i<5
Computer control statement: If/Else
Actual result:
First Input -> a
Computer control statement: If/Else
No valid option
Second input -> b
Computer control statement: Switch
No valid option
Third input -> a
Computer control statement: If/Else
Program ends.
I expect default statement to be skipped since break statement is applied.
Is this happening as System.in.read() returns a new line?
I think same behaviour is to be expected from while; do-while loops?
It's not as easy as #Arvind Kumar Avinash says, depending on your OS you may encounter either a \r (carriage return), \n (new line) or both \r\n after every line.
So just adding another System.in.read() line is a workaround that may not always work.
I suggest using Scanner instead, as suggested here: Take a char input from the Scanner.
LE: As an answer to a request in the comment, I would like to specify that I always try to use Scanner when I want to parse my input and don't mind the performance. When I mind performance, I use BufferedReader. Never System.in directly. You can read more in the answers provided here https://stackoverflow.com/a/21698084/2477456.
I believe the answer is a combination between the 2 answers offered so far.
For a quick fix, #Arvind Kumar Avinash is very good.
Looking more in to the problem as #Valdrinium specifies alternatives might be considered.
I am sceptical on choosing #Arvind Kumar Avinash as definitive, although it solve the problem in this instance.
Can an admin help?
It's happening because of the dangling line break character. Just add System.in.read(); once again as shown below to consume dangling line break character e.g. (char) System.in.read() consumes just a but not the Enter character that you press after a.
public class Main {
public static void main(String[] args) throws java.io.IOException {
System.out.println("Menu: ");
System.out.println("Choice: ");
System.out.println("1: If/Else");
System.out.println("2: Switch");
for (int i = 0; i < 5; i++) {
chooseOption();
}
}
static void chooseOption() throws java.io.IOException {
char choice = (char) System.in.read();
System.in.read();// Add this line
switch (choice) {
case 'a':
System.out.println("Computer control statement: If/Else");
break;
case 'b':
System.out.println("Computer control statement: Switch");
break;
default:
System.out.println("No valid option");
}
}
}
A sample run:
Menu:
Choice:
1: If/Else
2: Switch
a
Computer control statement: If/Else
b
Computer control statement: Switch
a
Computer control statement: If/Else
b
Computer control statement: Switch
a
Computer control statement: If/Else

I'm having issues with leading zeros

I'm attempting to get this to recognize the leading zeros in my program, and I thought using 'String.format("%03d", code);' would take care of it but I'm still not getting the expected result.
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String args[]){
Scanner sc =new Scanner(System.in);
System.out.println("Enter the shipment code :");
int code = sc.nextInt();
String.format("%03d", code);
// fill the code
if( code == 111 ){
System.out.println("All ways");
}
else if( code == 110){
System.out.println("Airway and Waterway");
}
else if( code == 011){
System.out.println("Waterway and Roadway");
}
else if( code == 010){
System.out.println("Waterway");
}
else if( code == 101){
System.out.println("Airway and Roadway");
}
else if(code == 001){
System.out.println("Roadway");
}
}
}
You're doing something wrong here.
011, 010, 001 are octal numbers, as they start with a zero.
Also, using String.format is pointless here, as the resulting value is not used.
This might be why your if branches aren't taken into consideration.
final String formattedValue = String.format("%03d", code);
Now you can use formattedValue as a comparison value for your if statements.
Example
if ("111".equals(formattedValue)) { ... }
Note that maybe transforming the int into a String isn't necessary. But in case you insist on doing so, a good practice is to use a constant String as the operand which calls equals(...).
You're discarding the formatted value. You need to store it in a variable and compare it as string:
String formatted = String.format("%03d", code);
if( formatted.equals("111") ){
System.out.println("All ways");
}
// ...
Well, String.format("%03d", code), returns a string, and you are comparing to integers (octal integers, as LppEdd pointed out).
You should store the formatted string to a variable, e.g.
String formatted = String.format("%03d", code);
and then compare it to Strings in your if/else statements, like so:
if(formatted.equals("011")) {...}
Don't format and remove any leading 0's in the condition and use switch
int code = sc.nextInt();
// fill the code
switch(code) {
case 111:
System.out.println("All ways");
break;
case 110:
System.out.println("Airway and Waterway");
break;
case 11:
System.out.println("Waterway and Roadway");
break;
case 10:
System.out.println("Waterway");
break;
case 101:
System.out.println("Airway and Roadway");
break;
case 1:
System.out.println("Roadway");
break;
default:
System.out.println("Unknown code " + code);
break;
}

The operator || is undefined for the argument type

Java is really confusing me with its brackets and variables and I know with just a little help I can understand what the problem is and get on with it.
if(value1=||
Is where the error is.
Apologize in advance that indenting 8 spaces appears to have not had this pull in correctly either. help with that also appreciated...
import java.util.Scanner;
public class WTF {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("Please enter your Character");
String value1 =input.toString();
if (value1 ="a"||"A"||"e"||"E"||"i"||"I"||"o"||"O"||"u"||"U") {
System.out.print("You entered " +value1);
}
else System.out.print("Consonant");
}
}
You will have to check for every string seperately:
if (value1=="a"||value1=="A"||value1=="e"||value1=="E"||value1=="i"||value1=="I"||value1=="o"||value1=="O"||value1=="u"||value1=="U")
but this will most likely not work since == checks for identity on objects and not equality and String is an object. So you would have to write it like this:
if (value1.equals("a") || value1.equals("A") || value1.equals("e") || value1.equals("E") || value1.equals("i") || value1.equals("I") || value1.equals("o") || value1.equals("O") || value1.equals("u") || value1.equals("U")
This is just getting painfull so you could reduce this by setting value1 to upercase and just check for upercase values:
String value1_tmp = value1.toUperCase();
if (value1_tmp.equals("A") || value1_tmp.equals("E") || value1_tmp.equals("I") || value1_tmp.equals("O") || || value1_tmp.equals("U")
This is still kinda ugly so we can improve it by putting it in a method and using a switch statement
private static boolean isVowel(String s) {
switch(s.toUperCase()) {
case "A":
case "E":
case "I":
case "O":
case "U":
return true;
default:
return false;
}
}
and then use this method in your if check:
if (isVowel(value1)) { ...
Or if you are a fan of regular expressions simply do:
if (value1.matches("(?i)[aeiou]")) { ...
So many options, just choose one :)
EDIT: Also fix what Djehenghizz mentioned. Instead of
String value1 = input.toString();
do
String value1 = input.nextLine();
Also, change String value1=input.toString(); into String value1=input.nextLine(); because input is already string, you dont have to transform it.
|| Logical OR Operator only used to combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true.
here what you trying to do is using || between two character types. so It will raise an compile time error actually.
Right Way to check is ==>
Scanner reader = new Scanner(System.in);
char c = reader.nextChar(); //Correct way to Read Char from Console.
private boolean checkVowel(char c) {
switch(c) {
case 'A':
case 'a'
case 'E':
case 'e'
case 'I':
case 'i'
case 'O':
case 'o':
case 'u':
case 'U':
return true;
default:
return false;
}
}
Use below code
public static void main(String[] args) {
List<String> vowelsList = Arrays.asList("a","A","e","E","i","I","o","O","u","U" );
Scanner input =new Scanner(System.in);
System.out.println("Please enter your Character");
String value1 = input.next();
if (vowelsList.contains(value1)) {
System.out.print("You entered " +value1);
}
else System.out.print("Consonant");
}
Try
if (value1=="a"||value1=="A"||value1=="e"||value1=="E"||value1=="i"||value1=="I"||value1=="o"||value1=="O"||value1=="u"||value1=="U") //...
Or
if ("aeiouAEIOU".contains(value1))//...
String value1 =input.toString();
it means use get the info about the input -- a instance of Scanner Class ,the target of it is not what you input.
you may use
String value1 = input.next();
or
String value1 = input.nextLine();
Boolean operator is used to check the value of two boolean variables and returns a boolean value here you are using the operator to compare two strings which is not compatible.
as said earlier you used input.toString method to get the instance of the scanner class but it's not compatilbe instead of that you can use input.Read() or input.ReadLine().
For Strings you should use the .equals("Your Text here") method. should look like this:
if(value1.equals("a")||value1.equals("A")||value1.equals("e"))
and so on.

Invalid character statement case value in switch statement

My code is telling me that the case 'A+' is an invalid character statement, but I need to be able to have case A+, A, A- and so on. What I'm wondering is: can I not have + or - inside the case value at all? and if so, is there any other way to identify what the user inputs into the console. I haven't been able to find an answer browsing around. Help is appreciated!
import java.util.Scanner;
public class GradeAdvice {
public static void main(String[] args) {
// User will input grade and program will give advice corresponding
// to that grade
// Prompt use for their grade
System.out.println("What was your grade on the midterm?");
char midtermGrade;
// Create an input object
Scanner input = new Scanner(System.in);
midtermGrade = input.next().charAt(0);
// Determine which advice to give based on grade
switch (midtermGrade)
{
case 'A+' :
case 'a+' : System.out.println("Continue doing what you have been doing, ask questions");
break;
default: System.out.println("This grade is invalid.");
break;
}
// Close input
input.close();
}
}
Character literals in Java identify one character, not multiple characters, within single-quotes. For multiple characters, you must use a String, delimited by double-quote characters.
In Java 7+, you can use Strings as case labels, e.g.
case "A+":
But you are only using the first character of input. Change
char midtermGrade;
midtermGrade = input.next().charAt(0);
to
String midtermGrade;
midtermGrade = input.next();
A char can hold a single character. Instead, you could just use a String:
String midtermGrade;
// Create an input object
Scanner input = new Scanner(System.in);
midtermGrade = input.next();
// Determine which advice to give based on grade
switch (midtermGrade)
{
// Note that strings are denoted by "s, not 's.
case "A+" :
case "a+" : System.out.println("Continue doing what you have been doing, ask questions");
break;
default: System.out.println("This grade is invalid.");
break;
}
Use String, and normalize the case
switch( input.next().toUpperCase() )
{
case "A+" :
...
default :
...
}
"A+", double quotes for string, single quote for character.
This is because you are using a character instead of a string. A character is exactly what it says, one character. A+ is two characters A and +. Use double quotes (") for string literals. For example:
'A' \\ This is a character
"A" \\ This is a string
"A+" is not char , it is string define it as string .
A+ is a string, not a character. You could've done this in C# (using " rather than '), but not in Java, nor most other languages. Simplest way out for you is probably to convert the switch into a series of 'if' statements.

Switchstatement stops reading at white spaces

So I'm having a problem doing an assignment for my java class. The purpose is to create a program that uses a switch statement to convert letters from a string to their phonetics. i.e, A or a becomes Alpha.
The problem I'm having is the switch statement stops reading at the first whitespace in the string. How do i get it to continue reading the string without stopping at whitespaces
(i.e " ")?
Basically user inputs a string "Hi Hi" the output should be "Hotel Indiana Hotel Indiana"
The problem I'm having is it only gives "Hotel Indiana" stopping at the first whitespace i think at least.
This is the code i have so far:(I cut out most of the letters/numbers to save space and kept what i thought was most important for answering the question.)
import java.util.*;
public class SwitchStatement {
/**
* #param args
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter a message: ");
String message = keyboard.next();
for(int i = 0 ; i < message.length(); i++)
switch(message.charAt(i)) {
case 'a':
case 'A':
System.out.print("Alpha");
break;
case 'b':
case 'B':
System.out.print("Bravo");
break;
case ' ':
System.out.print(" ");
break;
default:
System.out.print(message.charAt(i));
break;
}
}
}
Thanks in advance for the help.
String message = keyboard.next(); reads one word at the time of call separated by space (" ").
Use String message = keyboard.nextLine(); to read the whole line including spaces within.
You should use nextLine. If you use next() deliminator comes in to picture which is space char. So eventually you end up reading only one token not full string.
String message = keyboard.nextLine();
e.g For below string
A a B b
keyboard.next()---> will return you A if you again call then B and so on
keyboard.nextLine()-->will return you whole line ie. A a B b which you want

Categories