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!

BackSlash
  • 21,927
  • 22
  • 96
  • 136
Geabus
  • 61
  • 4
  • 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. – BackSlash Nov 05 '13 at 17:34

2 Answers2

3

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012
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:

Community
  • 1
  • 1
Fritz
  • 9,987
  • 4
  • 30
  • 49
  • I played around with apend and it is super useful, I can see myself using it a lot in the future. Thanks! – Geabus Nov 06 '13 at 00:12
  • @user2957372 You're welcome. Just remember the way we roll here: [upvotes](http://stackoverflow.com/help/privileges/vote-up) and [accepting answers](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – Fritz Nov 06 '13 at 12:31