开发者社区> 问答> 正文

从while循环退出在Java中不起作用

我是Java编程的新手。如果用户输入“ N”,我想计算和并退出程序,如果用户输入“ Y”,则想再次循环。但是,即使我输入“ N”也不能使我脱离循环”。

public class Program {



    public static void main(String[] args) {
        boolean a=true;
        while (a) {
        System.out.println("enter a number");
        Scanner c=new Scanner(System.in);
        int d=c.nextInt();

        System.out.println("enter a number2");
        Scanner ce=new Scanner(System.in);
        int df=ce.nextInt();

        int kk=d+df;
        System.out.println("total sum is"+kk);

        System.out.println("do you want to continue(y/n)?");
        Scanner zz=new Scanner(System.in);
        boolean kkw=zz.hasNext();
        if(kkw) {
           a=true;
        }
        else {
            a=false;
            System.exit(0);
        }
        }
}

我不知道我在哪里犯了错误?还有其他办法吗?

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 13:57:15 1387 0
2 条回答
写回答
取消 提交回答
  • 个人对建模比较关注

    给一个排查思路,也就是别人为什么能帮你查出问题,去debug一下你的代码,看清楚每个步骤产生什么结果,你就会发现问题在哪里了。

    2020-03-25 17:22:54
    赞同 展开评论 打赏
  • 首先,你的a变量是真,如果scanner.hasNext()是真的,导致a正在true与每个输入,包括"N"它的手段,你的while循环将继续下去,直到有没有更多的投入。

    其次,您可以通过以下方式优化代码:

    1. 我建议除暴安良a,并kkw让你的代码更清洁和更短。
    2. 仅使用一个Scanner,然后在循环外部进行定义。Scanner对于相同的输入,您不需要多个。另外,Scanner用每个循环初始化a 都是资源消耗。
    3. 使用有意义的变量名。编程不仅应该高效,而且还应易于阅读。在这个很小的代码中,这是一个小问题,但是可以想象拥有一个完整的程序,而不必添加功能和错误修复,而必须搜索每个变量的含义。 这是代码的优化且有效的版本:
    Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.println("Enter a number");
        int input1 = scanner.nextInt();
        scanner.nextLine(); // nextInt() doesn't move to the next line
    
        System.out.println("Enter a second number:");
        int input2 = scanner.nextInt();
        scanner.nextLine();
    
        System.out.println("Total sum is " + (input1 + input2)); /* Important to 
        surround the sum with brackets in order to tell the compiler that 
        input1 + input2 is a calculation and not an appending of
        "Total sum is "*/
    
        System.out.println("Do you want to continue? (Y/N)");
        if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
            break;
    }
    scanner.close();
    

    回答来源:Stack Overflow

    2020-03-22 13:58:06
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载