简体   繁体   中英

Im supposed to take a number entered from user to check if the input is a prime number or not.(I started very recently so please dont judge).)

Please try to base examples or explanations off of my code as I am a beginner there are many concepts that I do not understand.

import java.util.*;
public class Main{    
public static void main(String[]args){
while(true) {  
    int i;
    int x;
    System.out.println("Enter a number.");
    Scanner input = new Scanner(System.in);
    int z = input.nextInt();
    x=z/2;      
}

for(int i=2; i <= int x ; i++)
if(z%i==0||z==0||z==1){
    System.out.println("Not prime number");
    }
else{
    System.out.println("Prime Number");
    }  
}           

    

Add isPrime() function that checks if the number is prime or not and print in the while-loop

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.println("Enter a number.");
            int num = input.nextInt();
            if (isPrime(num)) {
                System.out.println("Prime Number");
            } else {
                System.out.println("Not prime Number");
            }
        }
    }

    private static boolean isPrime(int num) {
        if (num == 0 || num == 1)
            return false;
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM