1

I'm having trouble with a while loop in a Java program. I want to have a loop that has endless input until a certain input is reached, as an example if you run the program it would look like this "Enter a letter" (user enters b) "Your current input is B" "Enter another letter" (user enters c) "Your current input is BC"

My loop:

while (myLock.open() == false) {

    System.out.println("Enter a letter: ");

    String inputString = myScan.nextLine();
    char inputTwo = inputString.charAt(0);
    String inputStringKeeper = inputStringKeeper + inputTwo;

    inputTwo = ' ';
    System.out.println(myLock.setValue(inputStringKeeper) + " your current combo is " + inputStringKeeper);
}

just FYI the myLock method is a method that unlocks a "padlock" when a certain input is reached and will say either "unlocked" or "still locked" Sorry for the jumbled post, so hard to explain over text. Thanks!

1
  • 1
    Please don't link to pastebin, paste the code here. If the pastebin link goes down permanently, no one will be able to see the linked resource anymore. Commented Nov 5, 2013 at 17:34

2 Answers 2

3

You need to move the declaration of inputStringKeeper outside the loop.

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

Comments

1

Keep track of the scope of the variables you define. In this case, inputStringKeeper lives as long as the current iteration, meaning that future iterations will have their own inputStringKeeper (since you create a new one every time).

If you want to have a common variable for all the particular steps of that while's iteration, define it outside of the block and use it inside.


Unrelated, but I might as well point some things out. Rather than using myLock.open() == false, use the unary (logical) operator not (!):

while(!myLock.isOpen())

It does the same, but it's easier to read.

Second, this is a good scenario to use a StringBuilder to avoid creating and storing a new String in the pool each time you concatenate a value.

StringBuilder inputStringKeeper = new StringBuilder();

Then, use the append function. This will handle the concatenation for you. Finally use the good'ol toString to get the String from the builder.


Some notions you might be interested into:

2 Comments

I played around with apend and it is super useful, I can see myself using it a lot in the future. Thanks!
@user2957372 You're welcome. Just remember the way we roll here: upvotes and accepting answers.

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.