This is simple code but I am not able to figure out why it is accepting two lines of input:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String inputString = scan.nextLine();
int n = Integer.parseInt (inputString);
for (int i = 1; i <= n; ++i) {
inputString = scan.nextLine();
int num = Integer.parseInt (inputString);
System.out.println ("Checking prime of: " + num);
for (int j = 2; j*j < num; ++j) {
if (num % j == 0) {
System.out.println ("Not prime");
break;
}
}
System.out.println ("Prime");
}
}
}
Now when I run with the following input:
3
12
5
7
The program prints the following:
Checking prime of: 12
Not prime
Prime
Checking prime of: 5
Prime
Checking prime of: 7
Prime
Note the second Prime above when it has not consumed any input.
I must be making a simple mistake but not able to figure out what is wrong. If someone could point out what I am doing wrong that would be much appreciated.
System.out.println ("Prime");after theforloop so it always prints "Prime", no matter what you enter and whether the actual number is a prime or not. Note that thebreak;in the innerforloop only jumps out of the inner loop, not out of the outer loop.