简体   繁体   中英

Exiting from while loop not working in java

I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "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);
        }
        }
}

I didnt know where I made the mistake? Is there any other way?

First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.

Second of all, you could optimize your code the next way:

  1. I suggest getting rid of a and kkw to make your code cleaner and shorter.
  2. Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
  3. Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.

Here's an optimized and working version of your code:

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();
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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM