I am new to java programming, I have programmed in C and C++ but have moved to Java recently, So I am a bit confuse about how things are in Java. I am calling a function inside my main but the program gets terminated, I don't know why its happening and can't figure it out. Here is my program
package Prime;
import java.util.Scanner;
public class isprime
{
public static boolean isPrime (int n)
{
int flag=0;
for (int i=2;i<=n;i++)
{
if(i%n==0)
{
flag=1;
}
}
if(flag==1)
{
return false;
}
else
{
return true;
}
}
public static void main(String[] args)
{
int n;
System.out.println("Please enter a number you want to test");
Scanner sc = new Scanner(System.in);
sc.close();
isPrime(n);
}
n = sc.nextInt();
}
Your n = sc.nextInt();
is outside the scope of main()
function. Moreover your are closing the scanner first.
You called isPrime(n);
which returns boolean
but you did not catch the return
value.
You want to do something like:
public static void main(String[] args) {
int n;
System.out.println("Please enter a number you want to test");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
if (isPrime(n)) {
System.out.println("prime");
} else {
System.out.println("not prime");
}
sc.close();
}
Finally , your prime calculation is wrong. A prime number is divisible by itself, so change
for (int i=2;i<=n;i++)
to
for (int i=2;i < n;i++)
^^^
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.