public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isprime;
isprime = true;
int i = 2;
if (number <= 1) {
System.out.println("The number is not prime");
} else {
while (i <= number / 2 && isprime) {
if (number % i == 0) {
isprime = false;
}
i++;
}
if (isprime == true)
System.out.print("the number is prime number");
else
System.out.println(("the number is not prime number"));
}
}
Greetings,
There are several techniques to incorporate here to declutter your code, eliminate unnecessary lines, make it simpler, and avoid bugs. Here are some tips:
Use declaration and initialization on the same line. Example boolean isprime: true;
Declare and initialize variables where and when they will be used. Example: your boolean isprime should be inside your first if statement. Almost all these elements could be inside a method.
Avoid adding if statements where your flags and checks can be used at the end of an operation. For example, the last two print() operations can be used within your first if and else statements.
Avoid repeating code. The number is not prime flag could be used once if you review the logic for checking if a number is prime.
Remember the difference between the == operator and the isEqual() method. One is comparing the location in memory (with some exceptions) and the other is comparing the value stored at the address.
Use conventional nomenclature for variables, classes, or methods. It makes your code cleaner and easier to read. For example, your variable isprime should be written isPrime instead.
Java syntax allows simplicity. For example, isprime = false; is the same as !isprime;. Since you had initialized your variable as true.
Thank you so much! I’ve been waiting for someone to critique my code. I know it works, but I’m aware it could be written much better. I’ll make sure to follow your notes.
I recommend that you watch the amazing YouTube videos on coding paradigms and practices by the Youtubers Fireship, Coderized, and CodeAesthetic.
Click on those names. I linked some of their videos to give you some guidance. Do not be intimidated by the potentially “out of your league” subjects covered. Watch the videos. They will give you a great head start, and point you in the right directions. These three channels are my all time favorites. Fireship give expert and straight to the point tips. CodeAesthetic gives expert step by step beautiful demonstrations. And Coderized gives expert and paced explanations with visuals similar to those of CodeAesthetic. You will love them.
One extremely helpful video from the YouTube channel Low level Learning, about how NASA produces error free code.