Home > Blockchain >  Take integer inputs till the user enters 0 and print the sum of all numbers (HINT: while loop) (codi
Take integer inputs till the user enters 0 and print the sum of all numbers (HINT: while loop) (codi

Time:11-06

IN this problem we have to print the sum of all the numbers until the user enters zero.

my attempt:

import java.util.Scanner;

public class printsum_until_enter0 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int sum = 0;
        //int count = 0;
        int x = in.nextInt();
        while (x >0) {
            if (x > 0) {

                sum = sum   x;
                System.out.println(sum);
                x--;

            } else {
                System.out.println("no data was entered");

            }

            x--;
        }

    }
}

it runs infinitly before writing X--...but now it takes only one input and after that it is executed...but it supposed to execute after entering 0 and sum of all the numbers before entering 0. But it is not happeing.Any solution guys...Code in java..

CodePudding user response:

Fixed your code

   package test1;
    import java.util.Scanner;
    public class printsum_until_enter0 {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int sum = 0;
            int x = in.nextInt();
            while (x >0) {
                if (x > 0) {
                    sum = sum   x;
                } else {
                    System.out.println("no data was entered");
                }
                x = in.nextInt();
            }
            System.out.println(sum);
        }
    }

CodePudding user response:

do {
  x = in.nextInt();
  if(x > 0) {
    sum =  x;
  }
} while(x > 0)

CodePudding user response:

Your problem is that you only ask the user for input once. What you want to do is move the scanner.nextInt part somehow into your loop. In java there is a concept called do while loop which executes the loop body first and then checks the loop condition if it should be repeated. If you do not want to use a do while loop you can use a while true loop to check if the input was 0 and exit. Notice also how x needs to be initialised before the function body to be recognized by the while statement

Unfortunately, I did not get why you decreased x in your code. Let me know if I misunderstood your question or you have any more questions

import java.util.Scanner;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int sum = 0;
        int x = 0;

        do {
            System.out.println("Please insert a number: ");
            x = in.nextInt();

            // If x is 0 it wont change the sum
            sum  = x;
            System.out.println(sum);

        } while (x > 0);

        System.out.println("no data was entered");

    }

}
  •  Tags:  
  • java
  • Related