Saturday, 4 November 2023

Write a java Program to accept ‘n’ no’s through command line and store only armstrong no’s into the array and display that array.- Core Java Slip 17

 

Write a java Program to accept ‘n’ no’s through command line and store only Armstrong no’s into the array and display that array.

import java.util.ArrayList;

import java.io.*;

public class ArmstrongNumbers {

    public static void main(String[] args) {

        if (args.length == 0) {

            System.out.println("Please provide some numbers as command-line arguments.");

            return;

        }

 

        int n = args.length;

        int[] numbers = new int[n];

 

        for (int i = 0; i < n; i++) {

            try {

                numbers[i] = Integer.parseInt(args[i]);

            } catch (NumberFormatException e) {

                System.out.println("Invalid input: " + args[i] + " is not a valid number.");

                return;

            }

        }

 

        ArrayList<Integer> armstrongNumbers = new ArrayList<>();

        for (int number : numbers) {

            if (isArmstrongNumber(number)) {

                armstrongNumbers.add(number);

            }

        }

 

        if (armstrongNumbers.isEmpty()) {

            System.out.println("No Armstrong numbers found in the provided input.");

        } else {

            System.out.println("Armstrong numbers in the input:");

            for (int armstrongNumber : armstrongNumbers) {

                System.out.println(armstrongNumber);

            }

        }

    }

 

    public static boolean isArmstrongNumber(int number) {

        int originalNumber, remainder, result = 0;

        originalNumber = number;

 

        while (originalNumber != 0) {

            remainder = originalNumber % 10;

            result += Math.pow(remainder, 3);

            originalNumber /= 10;

        }

 

        return result == number;

    }

}