Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While Loop executing one last time when condition is set to false

Task: To check that if a user input string has the same first and last character. If yes or no, output to the screen, if the user enters "done", the loop is exited.

Issue: While loop executes when condition is false

What I've tried: Using different types of loops, doing a loop within the loop to revalidate the code and all together giving up!

import java.util.*; 


public class lab_15 {
  public static void main(String args[]) { 
    String userInput = "";
    String done = "done";    
    while (!userInput.equalsIgnoreCase(done))
    {
        int length;
        Scanner sc = new Scanner(System.in); 
        userInput = sc.next();
        length = (int)userInput.length();

        if (userInput.charAt(0) == userInput.charAt(userInput.length()-1)) {
            System.out.println("The first character equals the second character.");
        }
        else {
            System.out.println("The first and second characters are different.");
        }
    }
    // EXIT LOOP
    System.out.println("Thank you for using this software!");
  }
}

Inputs + bradley + hannah + done

I am still new to the site and have referred to the t's & c's regarding posts. Please do not negative if you find the question to not be challenging. I am new to programming and hope to progress.

Thank you!!!

like image 678
bradleyduncan Avatar asked Feb 11 '26 19:02

bradleyduncan


1 Answers

This is because you change your userInput immediately once entering the loop. The condition is only checked when you reach the top of the loop, so if you invalidate the condition halfway through, it will continue executing until you reach the top.

The solution is to refactor so that the very last thing that happens is changing your userInput so that the condition is check immediately after the value is changed. (I would also pull the scanner instantiation out of the loop.)

Alternatively you could check your condition inside of the while loop and call break if the userInput has changed to match the terminating condition. The break keyword will force the logic to exit the loop immediately, without evaluating the condition again.

like image 190
Roddy of the Frozen Peas Avatar answered Feb 13 '26 10:02

Roddy of the Frozen Peas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!