samedi 19 mai 2018

Why doesn't my if statement work on a string that has been read from the client? [duplicate]

This question already has an answer here:

When I input from my client through localhost onto my server I made in Java, it somehow doesn't register the String after reading the instream, although it prints it. The code that does this is

while (true){
            middleman = new ServerSocket(port);
            client = middleman.accept();
            middleman.close();
            PrintWriter out = new PrintWriter(client.getOutputStream(),true);
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String line;
            while((line = in.readLine()) != null)
            {
                System.out.println("echo: " + line);

                //Response
                if(line == "cupcake"){
                    System.out.println("you are correct!");
                }
                else{
                    System.out.println("wrong!, the line is:" + line);
                }
            }
        }

When I type in "cupcake" from the client, it will print on the server side

echo: cupcake
wrong!, the line is:cupcake

What's going on here? I tried making a separate String variable within the while loop and setting it to 'line', but it doesn't work either.

Aucun commentaire:

Enregistrer un commentaire