0

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?

4

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reminder, I haven't used Scanner for ages. Also, I didn't say it's an error, it's solely a suggestion.
@user85421 could you please edit my answer regarding the hasNext() issue?
0
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();
}

3 Comments

You should absolutely close the Scanner. Using System.in is the failing, but it doesn't matter since this is throw away code. Ideally, the program would open a dedicated stream.
Never leave resources open. It's programming 101. It invites memory leaks. Even if it's something silly like a ByteArrayOutputStream, you should always be in the habit of closing it.
You should absolutely not close the Scanner. You should always close every resource you open, but you did not open System.in, so you should not close it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.