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");
}
Related
I am using a switch statement which worked fine. But if something like an exception occurs inside the switch I want the program to return to ask for the users selection again.
I'll share some example code:
while (valid != true)
{
System.out.println("Enter a Choice \n1. Choice 1. \n2. Choice 2. \n3. Choice 3.");
int choice = getChoice(); //Get choice just returns an integer from user input.
switch (choice)
{
case 1:
//Do something
valid = true;
break;
case 2:
//Do something
valid = true;
break;
case 3:
//Do something
valid = true;
break;
default:
System.out.println("Invalid Choice.");
}
So if something went wrong and validChoice wasn't set to true. I want the user to be able to re-enter the choice but since the choice is already set. It will go to case 3 straight away.
Some things ive tried include:
All of these would be done if something goes wrong.
Setting choice to null for if it goes wrong. (Was hopeful that this would work) but java doesn't allow
Setting choice to 0 would just make it go to the default case.
Try this :
do {
System.out.println("Enter a Choice \n1. Choice 1. \n2. Choice 2. \n3. Choice 3.");
int choice = getChoice(); //Get choice just returns an integer from user input.
switch (choice)
{
case 1:
//Do something
valid = true;
break;
case 2:
//Do something
valid = true;
break;
case 3:
//Do something
valid = true;
break;
default:
System.out.println("Invalid Choice.");
break;
}
} while (valid != true);
}
}
I am trying to change the text in a TextView I am about to display, but if the input does not match any of the cases, I do not want to call the method.
How can I write this in as few lines of code as possible?
switch (integer) {
case 1:
case 2:
replyOne.setText("string 1 & 2");
break;
case 3:
replyOne.setText("string 3");
break;
default:
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
}
makeContactMessage(replyOne, messagesLayout);
In terms of fewer lines of code, just simply use if/else statements instead as follows:
if (integer == 1 || integer == 2) {
replyOne.setText("string 1 & 2");
} else if (integer == 3) {
replyOne.setText("string 3");
} else {
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
}
Keep things simple; no need to overcomplicate things :-)
Put the String logic in your Model and set the Textview only once. Your presenter should not have any logic.
String reply = model.getReply();
replyOne.setText(reply)
//in your model,
String getReply(){
switch(){
}
return ...
}
There are at least 2 ways to achieve that.
Using a return
Using a simple boolean flag.
.
1. Using a return
If your code is a method, you can use return statement something like this:
private void myCheckMethod(int value) {
switch (value) {
case 1:
case 2:
replyOne.setText("string 1 & 2");
break;
case 3:
replyOne.setText("string 3");
break;
default:
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
return; // here the method will be terminated if checking is not valid.
}
makeContactMessage(replyOne, messagesLayout);
}
2. Using a simple boolean flag.
Use a simple flag for calling the method. Here we using isValid variable:
boolean isValid = true; // always set checking as valid.
switch (integer) {
case 1:
case 2:
replyOne.setText("string 1 & 2");
break;
case 3:
replyOne.setText("string 3");
break;
default:
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
isValid = false; // false, because we can't match anything.
}
if(isValid) {
makeContactMessage(replyOne, messagesLayout);
}
My code looks like:
switch(read.nextInt()){
case 1:
//do "a" and print the result
break;
case 2:
//do "b" and print the result
break;
case 3:
//do "a" and print the result
//do "b" and print the result
}
Is there another way to do it without simply copying what's inside case 1 and 2?
I just started my graduation, so I can only use String and Scanner for this, thanks :)
Define two methods called doA() and doB() and call them. This way you won't duplicate your code. Also are you sure you don't need break statements after each case statement?
switch(read.nextInt()){
case 1:
doA();
break;
case 2:
doB();
break;
case 3:
doA();
doB();
break;
default:
// do something
break;
}
A tricky one, IMO more readable:
int nextInt = read.nextInt();
if (nextInt % 2 == 1) { // or if (nextInt == 1 || nextInt == 3) {
// do "a" and print the result
}
if (nextInt > 1) {
// do "b" and print the result
}
In cases like this it probably makes sense to create methods for
//do "a" and print the result
and
//do "b" and print the result
In case 3 you would just call these methods one after the other.
Looks like you've forgot about 'break'. It makes code "break" from switch statement. If you want in case of '1' & '2' do the same thing and in case of '3' the other thing, you can write:
switch(read.nextInt()){
case 1:
case 2:
//do "a" or "b" and print the result
break; //break from switch statement, otherwise, the code below (yes, I mean "case 3") will be executed too
case 3:
//do "a" and print the result
//do "b" and print the result
}
It is a usual thing to add "break" in the end of "case" block if you don't want the same code block to be executed for several values:
switch(n){
case 1:
//do something
break;
case 2:
//do other things
break;
case 3:
//more things!
//you may not write "break" in the last "case" if you want
}
I'm trying to make a switch statement in java but I get this error even though my syntax is correct: Syntax error on token "{", SwitchLabels expected after this tokenI know that I can use statements but my teacher told me to use switch as it's prettier to look at, so I've to use switch. I've tried to move the input=scan.next() but that gives me another errors
switch (true) {
input = scan.next();
case 1:
input.equals("T");
outToServer.writeBytes("T\r\n");
System.out.println(inFromServer.readLine());
break;
case 2:
input.equals("S");
outToServer.writeBytes("S\r\n");
System.out.println(inFromServer.readLine());
break;
case 3:
input.equals("Z");
outToServer.writeBytes("Z\r\n");
System.out.println(inFromServer.readLine());
break;
case 4:
input.equals("D");
System.out.println("Write a message");
text = scan.next();
outToServer.writeBytes("D " + text + "\r\n");
System.out.println(inFromServer.readLine());
break;
case 5:
input.equals("DW");
outToServer.writeBytes("DW\r\n");
System.out.println(inFromServer.readLine());
break;
case 6:
input.equals("RM20");
text = "RM20 4" + "\"" + text1 + "\" \"" + text2 + "\" \"" + text3 + "\"" + "\r\n";
outToServer.writeBytes(text);
System.out.println(inFromServer.readLine());
System.out.println(inFromServer.readLine());
break;
case 7:
input.equals("Q");
clientSocket.close();
System.out.println("The server is disconnected");
break;
}
Two immediate problems with the first two lines:
switch(true){
You can't switch on boolean values
input = scan.next();
You've got this line immediately within the switch statement - it needs to be within a case statement.
I suspect you want:
String input = scan.next();
switch (input) {
case "T":
...
break;
case "S":
...
break;
// Other cases
default:
...
break;
}
Or get rid of the input variable if you don't need it for anything else:
switch (scan.next()) {
(I'd also strongly advise you to revisit your indentation. While switch/case statements can be indented in a number of ways, your current approach is really hard to read, IMO.)
Given things like this in your original code:
case 7: input.equals("Q");
... it seems to me that you probably don't understand what a switch statement actually does. Stack Overflow isn't a good place to learn the basics of a language like that - I suggest you read the Java tutorial on switch, or a good book, or ask your teacher for more help.
Change the order from:
switch(true){
input = scan.next();
To
input = scan.next();
inputNumber = scan.nextInt();
switch(inputNumber){//or from java 7 use input directly but quote your case values.
switch(true){
`input = scan.next()`;// This is error line.
After switch statement case is required. and You are accepting value from user.
You can't do a switch statement with a boolean argument.
switch(true) is not a valid statement.
String switch are not allowed in Java 6 but are allowed in Java 7 and Java 8.
Also equals method return a boolean and you are not saving this.
Actually, your syntax is nowhere near correct.
You want to input the value first. Since Java 7, you can switch on a string.
So:
Input first.
Declare what you want to switch on. In this case, it's your input variable.
Then declare the cases. The declarations are not case i: input.equals("what you want"). They are simply case "what you want".
So, the equivalent of if statements such as
input = scan.next();
if ( input.equals("T") ) {
outToServer.writeBytes("T\r\n");
System.out.println(inFromServer.readLine());
} else if ( input.equals("S") ) {
outToServer.writeBytes("S\r\n");
System.out.println(inFromServer.readLine());
}
...
Is actually:
input = scan.next();
switch ( input ) {
case "T" :
outToServer.writeBytes("T\r\n");
System.out.println(inFromServer.readLine());
break;
case "S" :
outToServer.writeBytes("S\r\n");
System.out.println(inFromServer.readLine());
break;
...
}
And in fact, you can join together all the cases that do the same in a single case:
input = scan.next();
switch ( input ) {
case "T" :
case "S" :
... // More case labels that should be treated the same
outToServer.writeBytes(input + "\r\n");
System.out.println(inFromServer.readLine());
break;
... // Other, non-similar cases
}
I am trying to test if my user submits sensible data , which is later formatted to integer.
Where is the problem with the switch statement? :)
void convert(String str)
{
int i=0;
String x=str.startsWith();
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
int i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
You're switching on x which is a String - unless you're using Java 7, you can't use String in a Switch statement.
I expect the error is actually coming from str.startsWith(), where that method is expecting to take a String (which you're checking what it starts with) and returns a boolean, which you can't switch on either.
UPDATE Correcting your code to do what I think you're trying to do:
void convert(String str)
{
int i = 0;
switch (str.charAt(0)) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
Although the shorter way is just to do the Integer.parseInt call, and handling the NumberFormatException that may occur - then you don't need to do the switch at all.
void convert(String str)
{
try {
int i = Integer.parseInt(str);
System.out.println (i);
} catch (NumberFormatException e) {
System.out.println ("Should start with fixnumber");
}
}
You need to either return i; and convert the method signature from void to int, or otherwise expose the data in i to make it worthwhile.
x is a string and in case you test number.
try:
case "string1"
..
break;
case "string2"
..
break;
etc...
If you're trying to test to see if the string entered is an Integer, then I see no reason to have the switch() in the first place. It would be far better behavior to catch the exception raised when trying to work with the function.
Example:
void convert(String str) { // Heads-up: convert has <package> visibility
int i = 0;
try {
i = Integer.parseInt(str);
System.out.println(i);
} catch (NumberFormatException nfe) {
System.out.println ("Should start with fixnumber");
}
}
Your x is a String. The switch statement is attempting to compare it against integer values. You need something like this:
switch (Integer.parseInt(x))
{
// etc...
EDIT: Actually, now that I see that the string is supposed to be the result of a startsWith call, I'm totally confused about what this code is trying to do.