Home > Software design >  How should I rewrite the code for this program?
How should I rewrite the code for this program?

Time:09-22

The function of the program is to let the user know if a number is prime. The code compiles but the string does not print and I cannot type in any user input.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num=0;
        int i=2;
        
        System.out.print("Which number would you like to check?");
        num = sc.nextInt();
        
        while (i<=num) {
            if (i ==num || num==1||num==0)  {
                System.out.print("Is not prime");
            }
            else if (num%i==0){
                System.out.print("Is prime");
            }
            else {
                  i;
            }
        }

CodePudding user response:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num=0;
int c=0;  //A counter to store the number of factors


System.out.print("Which number would you like to check?");
num = sc.nextInt();

for(int i=1;i<=num/2;i  ){
  if(num % i==0)
     c  ;
}
if(c==1)
  System.out.print("Prime");
else
  System.out.print("Not Prime");
}
  • Related