osman - 6 months ago 54

Java Question

I do not understand the code.

Could someone explain me step by step (code by code)?

Note: The purpose of the method is to ask for and recieve user input;

followed by checking the number to see if it's a prime number.

`package prime;`

import java.util.Scanner;

public class primetime {

public static void main(String [] args){

Scanner input = new Scanner (System.in);

System.out.print("Enter a number: ");

int a = input.nextInt();

boolean primeNumber = true;

for ( int b = 2; b < a; b++){

int z = a%b;

if (z == 0){

primeNumber = false;

}

}

if (a == 1){

System.out.println("(Not a) Prime number (1) (Not all mathematicians count 1 as a prime number)");

}

if (primeNumber){

System.out.println("Prime number (" + a + ")" );

}

else{

System.out.println("Not a prime number (" + a + ")");

}

}

}

Answer

I think you understand the imports, so i will continue on the 'main' method:

A scanner (** new Scanner(System.in)**) is for taking inputs and transferring to Strings, ints,

`"Enter a number: "`

`a`

`nextInt()`

`boolean`

`primeNumber`

`true`

`2`

`a`

integer z is the leftovers of how much b fits in a (that operation is called ** Modulo** or

`%`

`primeNumber`

`false`

`primeNumber`

`if`