What's wrong with my switch statement? - java

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
}

Related

Trouble with switch statements?

I am just trying to write a program that generates a random year between 2000 and 2010, then reads off a space exploration fact that occurred in that year.
This is the code that I have written, however when I run it, no matter what year is generated, it just prints the last case (2010). How do I fix this?
import java.util.Random;
public class SpaceExploration {
public static void main(String[] args) {
int year =(int)(Math.random()*11) + 2000;
String eventString = "";
switch (year) {
case 2000: eventString = "2000: First spacecraft orbits an asteroid";
case 2001: eventString = "2001: First spacecraft lands on asteroid";
case 2002: eventString = "2002: N/A";
case 2003: eventString = "2003: Largest infrared telescope released";
case 2004: eventString = "2004: N/A";
case 2005: eventString = "2005: Spacecraft collies with comet";
case 2006: eventString = "2006: Spacecraft returns with collections from a comet";
case 2007: eventString = "2007: N/A";
case 2008: eventString = "2008: Kepler launched to study deep space";
case 2009: eventString = "2009: N/A";
case 2010: eventString = "2010: SpaceX sucessfully sends spacecraft to orbit and back";
}
System.out.println(eventString);
}
}
You need to add break statement after each case else after finding matching case it will just execute all cases until it finds break or the end which in your case is 2010.
Your code should look like:
switch (year) {
case 2000:
eventString = "2000: First spacecraft orbits an asteroid";
break;
case 2001:
eventString = "2001: First spacecraft lands on asteroid";
break;
...
notice the break after every case.
The other answers are correct, you have to introduce the break after every case.
In general you should also add the case default case and add some console output to make sure you're software is working as intended.
An alternative solution would be to use a HashMap:
Map<Integer, String> map = new HashMap<>();
map.put(2010, 2010: SpaceX sucessfully sends spacecraft to orbit and back);
...
String eventString = map.get(year);
Like this, you would enter the switch statement at the year you're providing and then fall-through all the way to the last case. That way, your eventString always contains the value of year 2010. To prevent this, simply add a break statement in each case.
Break is the keyword which is use to jump from the loop (while,do-while and for) and switch statements, break should be use when certain conditions matches and you want to come out from the loops or switch.
while(true){
if(true) {
break ; // when you want to get out from the loop
}
}
and for switch statements you should use break statements to get out from the loop.
What you have experienced is a feature of the switch statement called 'fall through'.
Although usually one uses the break variant (which makes sense in most cases) there are some applications to be executed in a defined order, falling through some cases in a waterfally manner. Look at the application below(link):
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year:
public class SwitchDemoFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
So if you want to get all space exploration facts that occurred in that year and later, you can omitt the breaks.

Switch Statement Help me Please

I'm kinda new to this but? can anyone correct my first switch statement? I dont know what expression to use to start the case a:
and im not even sure if the starting declarations are even correct
import java.io.*;
public class SwitchDemo {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input= br.readLine();
System.out.println("Press Enter");
System.out.println("a.Hello: Asks the name of the user.");
System.out.println("b.Array: Input elements and search for a specified key and prints a message.");
System.out.println("c.MagicSquare: Displays [7][7] magic square.");
System.out.println("d.Bubble Sort: Alphabetically sorts 20 employees using bubble sort.");
System.out.println("e.Selection Sort: Alphabetically sorts 20 employees using selection sort");
System.out.println("f.Insertion Sort: Alphabetically sorts 20 employees using Insertion sort");
System.out.println("g.Factorial: Run the Factorial application");
System.out.println("h.Triangle: Run the Triangle application.");
System.out.println("i.MergeSort: Performs the mergesort of a two class databasse.");
System.out.println("j.Stack_1: Perform reversal of string.");
System.out.println("k.Stack_2: Perform Infix Notation");
System.out.println("l.Postfix: Perform Postfix Notation");
System.out.println("m.Linked List");
System.out.println("n.Queue:");
System.out.println("o.Exit:");
switch (input) {
case a:
String usersName;
String upperCaseName;
TextIO.put("Please enter your name: ");
usersName = TextIO.getln();
upperCaseName = usersName.toUpperCase();
TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
break;
case b:
// Code for b execution here. Run array.
break;
case c:
// Code for c execution here. magicsquare.
break;
case d:
// Code for d execution here. Bubble sort.
break;
case e:
// Code for e execution here. selection sort.
break;
case f:
// Code for f execution here. insertion sort.
break;
case g:
// Code for g execution here. recursion.
break;
case h:
// Code for h execution here. mergesort.
break;
case i:
// Code for b execution here. stack1.
break;
case j:
// Code for b execution here. stack2.
break;
case k:
// Code for b execution here. link list.
break;
default:
System.out.println("Please input selection from a-o");
break;
}
}
}
As others have mentioned, using
switch(input) {
case "a":
// do stuff
break;
case "b":
// do more stuff
break;
}
will work.
Just another thing, if you are working in java 7 (java -version), you should be able to get rid of
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
and replace it with
Scanner in = new Scanner(System.in);
String input = in.nextLine();
Which at least to me is a lot easier to use. Just import
import java.util.Scanner;
A couple of points here
case statements are like this (pre 1.7)
char input = 'a';
switch (input) {
case 'a':
break;
default :
System.out.println("default");
}
for Java 1.7 and onwards you can also switch on Strings
String input = "a";
switch (input) {
case "a":
printHelloUser();
break;
default :
System.out.println("default");
}
void printHelloUser () {
String usersName;
String upperCaseName;
TextIO.put("Please enter your name: ");
usersName = TextIO.getln();
upperCaseName = usersName.toUpperCase();
TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
}
you may also want to consider prompting the user first before reading her input.
You aren't checking the cases as Strings (you declare input as a String). You are calling variables called a, b, etc. Try putting them into quotation marks, as in case: "a".

Switch Case Error Validation

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");
}

How to implement a special character(?) as an option in a Switch of type 'char'?

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.

Switch Statement is making the first case skip a line

So I'm guessing that the solution to this is going to be really simple but I have no idea what I'm looking for so I'd like some help. What happens is that when I run the program, and choose case 1. It prints both "dog's name" and "dogs race" without giving me a chance to fill in the dogs name. So when I choose case 1 I start out only getting to fill in dogs race, how heavy, and how old it is! here is the code I'm using...
do {
System.out.println("(1 - reg\n2 - tail\n3- delete\n4-exit\nEnter number: ");
// so this is where the switch stuff starts
int option=sc.nextInt();
switch (option) {
case 1: System.out.println("Dog's Name: ");
String na=sc.nextLine();
System.out.println("Dog Race: ");
String ra=sc.nextLine();
System.out.println("How heavy?");
double wey=sc.nextDouble();
System.out.println("How old?");
double ag=sc.nextDouble();
dog doggy= new dog(na, ra, wey, ag);
kennel.add(doggy);
break;
case 2: System.out.println("its a tail");
break;
case 3: System.out.println("you delete");
break;
case 4: System.out.println("QUITTING\n(Data was not saved srry.)");
play = false;
default: System.out.println("try again");
}
}while(play);
I believe you need to call nextLine() after your call to nextInt(), because that hasn't advanced the scanner to the next line yet.
There's a newline reminder from your first sc.nextInt, you can change the delimiter to \n or just call nextLine(); just after reading the option (Using sc.useDelimiter("\n") )
Try:
int option=Integer.parseInt(sc.nextLine());
This has both the effect of advancing the cursor to the next line and getting the typed number.

Categories

Resources