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 token
I 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.
See more on this question at Stackoverflow