Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để kiểm tra xem số đầu vào có phải là số Neon hay không

Trong bài này, chúng ta sẽ hiểu cách kiểm tra xem số đầu vào có phải là số neon hay không. Số neon là số có tổng các chữ số bình phương của số đó bằng số.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

9

Đầu ra

Đầu ra mong muốn sẽ như sau vì 92 =81, tức là 8 + 1 =9

The given input is a neon number

Thuật toán

Step1- Start
Step 2- Declare an integers my_input
Step 3- Prompt the user to enter an integer value/ Hardcode the integer
Step 4- Read the values
Step 5- Compute the square of the input and store it in a variable input_square
Step 6- Compute the sum of the of the digits of input_square and compare the result with my_input
Step 6- If the input matches, then the input number is a neon number
Step 7- If not, the input is not a neon number.
Step 8- Display the result
Step 9- Stop

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để kiểm tra xem số đầu vào có phải là số Neon hay không .

import java.util.Scanner;
public class NeonNumbers{
   public static void main(String[] args){
      int my_input, input_square, sum=0;
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("Required packages have been imported");
      System.out.println("A scanner object has been defined ");
      System.out.println("Enter the number: ");
      my_input=my_scanner.nextInt();
      input_square=my_input*my_input;
      while(input_square>0){
         sum=sum+input_square%10;
         input_square=input_square/10;
      }
      if(sum!=my_input)
         System.out.println("The given input is not a Neon number.");
      else
         System.out.println("The given input is Neon number.");
   }
}

Đầu ra

Required packages have been imported
A scanner object has been defined
Enter the number:
9
The given input is Neon number.

Ví dụ 2

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.

public class NeonNumbers{
   public static void main(String[] args){
      int my_input, input_square, sum=0;
      my_input= 9;
      System.out.printf("The number is %d ", my_input);
      input_square=my_input*my_input;
      while(input_square<0){
         sum=sum+input_square%10;
         input_square=input_square/10;
      }
      if(sum!=my_input)
         System.out.println("\nThe given input is not a Neon number.");
      else
         System.out.println("\nThe given input is Neon number.");
   }
}

Đầu ra

The number is 9
The given input is Neon number.