Java - Input 10 numbers and count total numbers where the fraction part is zero

By IncludeHelp Last updated : April 7, 2024

Problem statement

Write a Java program where we have to accept ten fractional numbers from the user and display and count the total numbers where the fraction part is zero.

Example

Input:
1.0
2.0
3.0
4.5
5.6
7.8
8.0
9.2
4.0
6.7
Output: Total numbers having its fractional part is zero: 5

Counting total numbers where the fraction part is zero from given numbers

To input numbers, use the nextDouble() method of Scanner class and to check and count the total numbers where the fraction part is zero, cast type the number in integer and then subtract it from the number. If it is 0 then increase the counter variable. The counter variable will be the result.

Java program to count total numbers where the fraction part is zero

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner objScanner = new Scanner(System.in);
    // Array to store 10  fractional numbers
    double[] numbers = new double[10];
    // variable to count numbers 
    // having 0 as fractional part
    int count = 0;

    // Input fractional numbers
    System.out.println("Input 10 fractional numbers:");
    for (int i = 0; i < 10; i++) {
      System.out.print("Number " + (i + 1) + ": ");
      // Input
      numbers[i] = objScanner.nextDouble();
    }

    // Printing the input fractional numbers
    System.out.println("\nThe fractional numbers are:");
    for (double num: numbers) {
      System.out.println(num);
      // checking if fractional part of a number is zero
      if ((num - (int) num) == 0) {
        count++;
      }
    }

    // Printing the count of numbers having 
    // zero fractional part
    System.out.println("\nTotal numbers having fractional part zero: " + count);
  }
}

Output

The output of the above program is:

RUN 1:
Input 10 fractional numbers:
Number 1: 1.0
Number 2: 2.0
Number 3: 3.0
Number 4: 4.5
Number 5: 5.6
Number 6: 7.8
Number 7: 8.0
Number 8: 9.2
Number 9: 4.0
Number 10: 6.7

The fractional numbers are:
1.0
2.0
3.0
4.5
5.6
7.8
8.0
9.2
4.0
6.7

Total numbers having fractional part zero: 5

RUN 2:
Input 10 fractional numbers:
Number 1: 1.1
Number 2: 2.2
Number 3: 3.3
Number 4: 4.4
Number 5: 5.5
Number 6: 6.6
Number 7: 7.7
Number 8: 8.8
Number 9: 9.9
Number 10: 1.0

The fractional numbers are:
1.1
2.2
3.3
4.4
5.5
6.6
7.7
8.8
9.9
1.0

Total numbers having fractional part zero: 1

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.