0

The loop I'm trying to run will initialize but will not continue to run after the first loop. Since I know where the problem i took out most of the code to fix the loop. After i make the second selection the loop will not run. Thank you for any help.

public static void main(String[] args)
{
  String number; // enter number        
  int stringLength = 0;    
  String selection = "y" ;
  // Create a Scanner object to read input.
  Scanner keyboard = new Scanner(System.in);

 // PrintWriter outputFile = new PrintWriter("outDataFile.txt");
 // outputFile.close();

  while (selection == "y")
  {

     // Get the user's number.
     System.out.print("Write your number ");
     number = keyboard.nextLine();


     System.out.print("y/Y to continue, any else to exit");
     selection = keyboard.nextLine();


  }

}  
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • Using `==` to compare strings does not do what you expect in Java. See [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Jesper Jul 07 '16 at 07:38

2 Answers2

2

Modify your condition:

while ("y".equalsIgnoreCase(selection.trim()))

It's better to compare String with equals so you compare the actual word instead he object identity. The trim will delete any blank space added by error

Also, it's better to compare with the constant "y" on the left side to avoid NullPointerException

Also, as in the other answer is explained, the equalsIgnoreCase() is important too.

raphaëλ
  • 6,393
  • 2
  • 29
  • 35
SCouto
  • 7,808
  • 5
  • 32
  • 49
  • 1
    Scanner.nextLine() should never return null, but you are right that one should compare to constant is the better approach. – aw-think Jul 07 '16 at 07:51
1

You should use equals instead of == for Strings as == compares only the references not the data inside the objects, so:

while (selection.equalsIgnoreCase("y"))

Ignoring case because you have "y/Y to continue, any else to exit" in your message.

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115