首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >退出不工作于java的while循环

问退出不工作于java的while循环
EN

Stack Overflow用户
提问于 2020-03-16 15:50:44
回答 2查看 67关注 0票数 0

我是java程序新手,我想计算和,如果用户输入"N“,我想退出程序;如果用户输入"Y".But,则再次循环,即使我输入"N”,也不能使我退出循环。

代码语言:javascript
复制
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);
        }
        }
}

我不知道我在哪里犯了这个错误?还有别的办法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-16 16:04:23

首先,如果a变量是真的,则scanner.hasNext()变量是真的,这导致a是带有每个输入(包括"N" )的true,这意味着您的while循环将继续进行,直到没有更多的输入。

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

  1. ,我建议去掉a和kkw,以使代码更简洁、更短。
  2. 只使用一个Scanner,并在循环的之外定义Scanner。对于相同的输入,您不需要多个Scanner。另外,用每个循环初始化一个resource-consuming.
  3. Use有意义的变量名。编程不仅要有效率,而且要容易阅读。在这段很小的代码中,这是一个小问题,但是想象一下有一个完整的程序,而不是添加特性和错误修复,您必须搜索每个变量的含义。

下面是您的代码的优化和工作版本:

代码语言:javascript
复制
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();
票数 4
EN

Stack Overflow用户

发布于 2020-03-16 16:08:22

代码语言:javascript
复制
try (Scanner in = new Scanner(System.in)) {
    boolean done = false;
    while (!done) {
        System.out.println("enter first number");
        int d = in.nextInt();
        System.out.println("enter second number");
        int df = in.nextInt();
        int kk = d + df;
        System.out.println(String.format("total sum is %d", kk));

        System.out.println("do you want to continue(y/n)?");
        String cont = in.next();
        done = cont.equalsIgnoreCase("n");

    }
} catch(Exception e) {
    e.printStackTrace();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60709118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档