-1

How come my while loop continues to print "Please enter stock length(mm): "

code:

while (true) {
            // input stocks
            System.out.print("Please enter stock length(mm): ");
            Scanner sc = new Scanner(System.in);
            int stockLength = sc.nextInt();
            System.out.print("Please enter quantities of this stock length: ");
            int stockQuantity = sc.nextInt();
            Stocks stockObj = new Stocks(stockLength,stockQuantity);
            stockList.add(stockObj);
            System.out.print("Are you done? (y/n): ");
            String done = sc.nextLine();
            if (done == "y" || done == "yes") {
                break;
            }
        }

Output:

Please enter stock length(mm): 4
Please enter quantities of this stock length: 4
Are you done? (y/n): Please enter stock length(mm): 
Liondancer
  • 15,721
  • 51
  • 149
  • 255

1 Answers1

4

Instead of sc.nextLine(), use sc.next()

String done = sc.next();
if (done.equalsIgnoreCase("y") || done.equalsIgnoreCase("yes")) {
     System.out.println("breaking out of loop " + "Value of done: " + done)
     break;
}
Susie
  • 5,038
  • 10
  • 53
  • 74