3

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!!!

bradleyduncan
  • 49
  • 2
  • 10

1 Answers1

4

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.

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99