当条件设置为false时,Loop最后一次执行

时间:2014-02-06 19:50:20

标签: java string while-loop

任务:检查用户输入字符串是否具有相同的第一个和最后一个字符。如果是或否,输出到屏幕,如果用户输入“完成”,则退出循环。

问题:while条件为false时循环执行

我尝试过:使用不同类型的循环,在循环中执行循环以重新验证代码并一起放弃!

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!");
  }
}

输入 +布拉德利 +汉娜 +完成

我还是该网站的新手,并提到了t& c关于帖子。如果您发现问题不具挑战性,请不要否定。我是编程新手,希望进步。

谢谢!!!

1 个答案:

答案 0 :(得分:3)

这是因为您在进入循环后立即更改userInput。只有在到达循环顶部时才会检查条件,因此如果您在中途使条件无效,它将继续执行直到您到达顶部。

解决方案是重构,以便最后发生的事情是更改userInput,以便在更改值后立即检查条件。 (我也会将扫描仪实例化拉出循环。)

或者,如果while已更改为与终止条件匹配,您可以检查break循环内的条件并致电userInputbreak关键字将强制逻辑立即退出循环,而不再评估条件。