osman osman - 1 month ago 3x
Java Question

Can somebody please explain this code?

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 + ")" );
System.out.println("Not a prime number (" + a + ")");



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, ... . Scanner a is one of them. Then it prints "Enter a number: ", And int a is the method of scanner called nextInt(). Then the client (the user) types a number. Then it creates a boolean called primeNumber and sets it to true. It creates a for loop that starts at 2, and repeats untill it's a. Then it does:

integer z is the leftovers of how much b fits in a (that operation is called Modulo or %). If z = 0, its even, so the sum b/a would be a hole number. Then primeNumber is false. At the end it check what primeNumber is. It prints the text that you can see in your code. I'm sure you know what if is (and i hope you can read the language of 'keine' or 'PrimZahl').