简体   繁体   中英

Resetting variable in loop

I have a client class where the value "number" should always be changing accordingly to be the user input but after each loop it stays the same as the first entry, ex: user input F next loop it will print F not anything but. I tried creating a new instance of it with the private method but I kept getting an enum error I didn't know how to approach.

public class Client {

public static void main(String args[]) throws UnknownHostException, IOException {
    boolean test = true;
    Socket s = new Socket("127.0.0.1", 6115);
    Scanner sc = new Scanner(System.in);
    Scanner sc1 = new Scanner(s.getInputStream());
    PrintStream p = new PrintStream(s.getOutputStream(), true);
    //String number;
    while (test) {
        String number;
        number = "";
        System.out.println("Enter any string");
        number = sc.nextLine();
        p.println(number);

        //flushing printstream not variable?
        number = sc1.nextLine();
        System.out.println("CALLED");
        System.out.println(number);
        p.flush();
        System.out.println("Would you like to enter another string? Y/N: ");
        String cont1 = sc.nextLine();
        if (cont1.equals("N")) {
            test = false;
            System.out.println("Goodbye! ");
        }
    }
    s.close();
    sc.close();
    sc1.close();
}
}
private void resetVariable() {
    Client = new Client();

}

The error is "Error:(43, 17) java: class, interface, or enum expected" which is puts the cursor right after void in the private object

then "Error:(46, 9) java: class, interface, or enum expected" highlighting the brackets in the private object

Move your method inside the Class:-

    } // This closes main
    //} // This was closing the Class Client
    private void resetVariable() {
        Client = new Client();

    } // This closes resetVariable
  } // This should now close Class Client

Update : From comments below - You should also think about instantiating the class Client from the member function resetVariable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM