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.
Related
I have been searching for this but couldn't find it. I want to get command moves input from user in Java using Scanner. The inputs the user can make are U(up), D(down), L(left), R(right). So for instance if the user writes UDULR (with nothing separating them) then I want to read in the letters separately. I tried like this:
String command;
char command;
Scanner scan = new Scanner(System.in);
System.out.println("Enter commands U(up),D(down),L(left),R(right);
//command = scan.next();
command = scan.next().charAt(0);
if(command == 'U'){
"Do this"
}
else if(command == 'D'){
"Do that"
}
When I use this code it only recognizes the first letter, (in this case I understand that charAt(0) represents the first letter). But how is it possible to get the other inputs? I tried both with String and char.
By default Scanner uses one or more whitespaces as delimiter, which separates tokens, so next returns token representing entire word, not single characters.
If you want next to return single non-whitespace characters then you can set delimiter to
series of whitespaces (\s+ in regex where \ needs to be written as "\\" in String)
or
empty string ""
But since zero OR one or more of X is same as zero or more of X, instead of + which in regex means "one or more occurrences", we can use * which represents "zero or more occurrences". So regex representing our delimiter may look like \s+ (which in String literal needs to be written as "\\s+" since \ needs to be escaped)
Demo:
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\s*");
System.out.println("Enter commands U(up),D(down),L(left),R(right)");
String command = scan.next();
if (command.equalsIgnoreCase("U")) {
System.out.println("Do this");
} else if (command.equalsIgnoreCase("D")) {
System.out.println("Do that");
} else {
System.out.println("unknown command: "+ command);
}
Based on your comment it looks like you want to handle group of commands passed as one word like UDULR which should move up, down, up, left and finally right. In that case you could organize your code like:
private void moveUp(){
//code for moving up:
System.out.println("moving up");
}
private void moveDown(){
//... similar
}
//rest of moving methods...
Now you can add one more method which will let chose which method to use based on char we pass to it:
public void move(char dirrection){
switch(dirrection){
case 'U' : moveUp(); break;
case 'D' : moveDown(); break;
case 'L' : moveLeft(); break;
case 'R' : moveRight(); break;
default: System.out.println("can't move in dirrection: "+dirrection);
}
}
Now in your code you should be able to use something like:
System.out.println("Enter commands U(up),D(down),L(left),R(right)");
String command = scan.next();
for (char directionCommand : command.toCharArray()){
move(directionCommand);
}
You need to save the result of next() in a variable; then you can use it to get any character in it in any order you want.
I have a scanner asking for some preferences. It creates an int variable choice between 0 and 3. Then I do the following:
String location;
switch(choice){
case 0:
System.out.println("Please type the zip codes you would like to search in a comma separated list");
location = input.nextLine();
break;
case 1:
System.out.println("Please type the street names you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
case 2:
System.out.println("Please type the boroughs you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
default:
location = "none";
break;
}
String locations[] = location.split("\\s*,\\s*");
now to me this seems perfectly fine, but when choice is set to 0,1, or 2 it will print the correct line, but skip the part where the user has to input something (the line that looks like location=...)
this means that it does not give the user the chance to enter anything and therefore locations becomes a blank list. Why does this happen and how can I fix it?
You are probably reading the newline after the last input, instead of the really next line. Try:
int choice = input.nextInt();
input.nextLine(); // <--- Eat it here!
String location;
switch(choice){
case 0:
Syst...
The nextInt() call, where you prompt the choice, does not end the line. So the first call to nextLine() after nextInt() is going to return an empty String. To fix that, eat the empty line after the integer and then move on.
I faced the same problem as you. Try:
case 'f' :
System.out.println("Enter a word or phrase to be found:");
scnr.nextLine();
String phrase = scnr.nextLine(); //
Put nextLine after the read before the switch.
System.out.print("Digite um número ente 1 e 9: ");
int opc = read.nextInt();
read.nextLine();
switch(opc) {
And read your value with nextLine()
case 6:
String[] procurados = read.nextLine().split(" ");
I'm just messing around in java and want to make a true or false trivia, what would be the best way to make the program accept the users input whether it starts with a lowercase or uppercase letter? (e.g. a true or false statement, that will accept either "True/false" or "true/false"). I tried looking on google but I can't find anything because I don't really know how to word it correctly.
I would do
String input =
if (input.equalsCaseIgnore("true")) // match any case combination of TrUe or trUE
If you are using a switch statement you can't do this but you can do
switch(input.toLowerCase()) {
case "true": // true in any case
break;
case "false": // false in any case
break;
default:
// handle error
break;
}
Something along these lines should work:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("false")) {
System.out.println("You input " + input);
}
else {
System.out.println("Input is invalid");
}
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;
}
}
}
}
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