我的switch语句出了什么问题?

Hod*_*hod -1 java switch-statement

我正在尝试在java中创建一个switch语句,但即使我的语法正确Syntax error on token "{", SwitchLabels expected after this token,我也会收到此错误:我知道我可以使用语句,但我的老师告诉我使用switch,因为它看起来更漂亮,所以我要去使用开关.我试图移动input=scan.next()但是这给了我另一个错误

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;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

前两行有两个直接问题:

switch(true){
Run Code Online (Sandbox Code Playgroud)

您无法打开boolean

input = scan.next();
Run Code Online (Sandbox Code Playgroud)

你在switch声明中立即得到了这一行- 它需要在一个case声明中.

我怀疑你想要:

String input = scan.next();
switch (input) {
    case "T":
        ...
        break;
    case "S":
        ...
        break;
    // Other cases
    default:
        ...
        break;
}
Run Code Online (Sandbox Code Playgroud)

input如果您不需要其他任何内容,请删除变量:

switch (scan.next()) {
Run Code Online (Sandbox Code Playgroud)

(我还强烈建议你重新审视你的缩进.虽然switch/case声明可以通过多种方式缩进,但目前的方法很难理解,IMO.)

在原始代码中给出类似这样的内容:

case 7: input.equals("Q");
Run Code Online (Sandbox Code Playgroud)

...在我看来,你可能不明白switch语句实际上是做什么的.Stack Overflow不是一个学习这种语言基础知识的好地方 - 我建议您阅读Java教程switch或一本好书,或者向老师寻求更多帮助.