Home > Mobile >  I a student at the moment cant figure out how to produce the answer while using while loops my issue
I a student at the moment cant figure out how to produce the answer while using while loops my issue

Time:07-04

Write a Java program that continues to read in integer numbers until the user enters the value -1 (sentinel). Your program should sum all the odd values entered and print the result when the loop ends.

import java.util.Scanner;

class trial {
  public static void main(String[] args) {
  
        int number;
        int sum = 0;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter a number");
        number = input.nextInt();
  
        while (number != -1){
            System.out.println("Enter a number");
            number = input.nextInt();
            sum  = number;
        }

        System.out.println("Sum = "   sum);
        input.close();

    }

}

CodePudding user response:

The % Operator works as modulo. Modulo will give you the indivisible remainder of the division of the second operand. Example 1 % 2 returns 1 and 4 % 2 returns 0

public static void main(String[] args) {
    boolean run = true;
    Scanner input = new Scanner(System.in);
    int number;
    int sum = 0;

    while (run){
        System.out.println("Enter a number");
        number = input.nextInt();

        if (number == -1){
            run = false;
            //checks if the number is not even or simply odd
        } else if (number % 2 != 0){
            sum  = number;
        }
    }

    System.out.println("Sum = "   sum);
    input.close();
}

CodePudding user response:

You can use modulo to perform an even/odd check. Therfor you have to check if this number divisible by two. So you get the rest of the division by 2: number % 2. If the number is even the result is 0 else 1. Put that into an if statement and you're good:

    int number;
    int sum = 0;

    Scanner input = new Scanner(System.in);

    System.out.println("Enter a number: ");

    while ((number = input.nextInt()) != -1){
        if (number % 2 != 0) //-> odd
            sum  = number;
        System.out.println("Enter a number: ");
    }

    System.out.println("Sum = "   sum);
    input.close();
  • Related