【问题标题】:Why does my Exception program keep running?为什么我的异常程序继续运行?
【发布时间】:2017-11-19 20:20:57
【问题描述】:

我有一个程序,但问题是即使我告诉它停止它仍然运行。我已经告诉它在布尔变量变为假时停止运行,但即使在变量变为假之后,程序也会继续运行。我发现程序继续运行的唯一方法是在 while 语句中取出“=true”部分。那么为什么我需要把语句中的“=true”部分去掉才能让程序正常运行呢?

import java.util.Scanner;

public class EvenOdd {

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int num;
        boolean continueLoop=true;
        do {
            try {
                System.out.println("Enter an even number");
                num=input.nextInt();
                if(num%2==0)
                 System.out.println("That is an even number");
                else
                 throw new IllegalArgumentException();
                continueLoop=false;
            }
            catch(IllegalArgumentException ae) {
                System.err.println(ae+"\nThat is a odd number");
            }
        } while(continueLoop=true);
        input.close();
    }

}

【问题讨论】:

  • continueLoop=true 是一个赋值,你总是在该行中将变量设置为 true。查找基本的 java 教程会告诉你:docs.oracle.com/javase/tutorial/java/nutsandbolts/…
  • 删除= true是适当的修复。比较 someBoolean == true 是多余的。只使用someBoolean 就足够了。
  • 仔细查看:while(continueLoop=true);
  • 你的错误在这一行---> while(continueLoop==true);输入.close(); }

标签: java exception while-loop do-while


【解决方案1】:

作为 while 循环的条件,您使用的是赋值而不是比较。

当您使用continueLoop=true 时,值true 被分配给continueLoop,循环简单地变成while(true);这是一个无限循环。

使用while(continueLoop == true),这是比较而不是赋值。

【讨论】:

    猜你喜欢
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    相关资源
    最近更新 更多