1

Is it at all possible to check if a String variable has changed since any two iterations of a while loop?

while (true) {    
    String player=json_obj.getString("username");
    System.out.println("Found Player "+player);
}

My reasoning for this is that a I don't want to keep printing out the player variable if it hasn't changed between each iteration of the while loop.

EDIT* Not sure why my post would receive a down vote since this is a valid question. *

2
  • 7
    You could add a "player in last iteration" variable that you compare with and which you fill after each iteration step. Commented Jan 30, 2017 at 12:29
  • 1
    Strings are immutable in Java, so you can't change it other than changing the object memory allocation segment that it points to. Commented Jan 30, 2017 at 12:45

3 Answers 3

2

Keep the previous value of player in another variable, and compare them :

String oldPlayer="";
while (true) {    
    String player = json_obj.getString("username");
    if (!player.equals(oldPlayer)) {
        System.out.println("Found Player "+player);
        oldPlayer = player;
    }
}

This is assuming your actual loop contains more logic, since based on the code you posted this loop will never end, and json_obj.getString("username") will always return the same value.

Sign up to request clarification or add additional context in comments.

Comments

2

The other answers are correct regarding how to do such checking.

But they are missing one crucial point: you don't just put down a while loop like

while (true) {
  String newValue = ...
  if (!newValue.equals(oldValue)) {...
}

without a sleep statement! The point is that any modern CPU can call that method to "get" the value zillions of time per second. But there is no point in doing that - because that simply pushes you to 100% CPU usage. Instead, you should allow for some time inbetween such calls.

And beyond that: I just assume that you have other code running in some other thread that actually changes those strings? If not, the above code will loop forever!

Comments

0

Well thats quite easy:

String oldValue = "";
while (true)
{
    String player=json_obj.getString("username");
    if (!oldValue.equals(player))
    {
        System.out.println("Found Player "+player);
        break; // quit loop when player found?
    }
    oldValue = player
}

When you're trying to wait for a value to change there are better ways (wait, and notify for example). If you want to do this anyhow think about not making the loop "busy waiting" with small sleeps at the end of every iteration

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.