I am very new at java coding. I am having difficulty finding out how to link my main
method with the method that determines if a value is prime. When I run the code below in eclipse, the method doesn't seem to execute at all. Does anyone know what I did wrong?
Also, for the last part I was thinking of having System.out
print whether the input value is prime or not. ie true
or false
would be fine.
import java.util.*;
class IsPrime {
public boolean isprime(int n) {
Scanner input1= new Scanner(System.in);
System.out.println("input single integer?");
int n1 = input1.nextInt();
int i,c=0;
for(i=1;i<=n1;i++) {
if(n1%i==0){
c++;
}
}
if(c==2) {
return true;
} else {
return false;
}
System.out.println("Your number is:")
}
}
System.out.println
after the method has returned - joshuahealy 2012-04-04 23:32
if (c==2) return ... else return ...
the System.out.println ("Your number is:")
is never reached - user unknown 2012-04-04 23:40
The line
System.out.println("Your number is:")
is unreachable as you have an
else {
return false;
}
before it.
First of all, what it's said by Strawberry and appclay is right.
In the other hand, your method isprime
is an instance method whilst your main
(I guess you talk about the method of your main class) is a class (static) method.
Try the following:
public static void main(String[] args) {
int possiblePrime = // initialise your parameter
IsPrime isPrime = new IsPrime();
boolean primeOrNot = isPrime.isprime(possiblePrime);
System.out.println("Your number is prime: " + primeOrNot);
}
If I understand what you're looking to is implement an isprime method and call it in a main.
class IsPrime {
public boolean isPrime(int n) {
int i,c=0;
for(i=1;i<=n;i++) {
if(n%i==0){
c++;
}
}
if(c==2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner input1= new Scanner(System.in);
System.out.println("input single integer?");
int n = input1.nextInt();
IsPrime isPrime = new IsPrime();
System.out.println("Your number is prime: " + isPrime.isPrime(n));
}
}
That should do what you want to do. However, there is a bug in your code. What you have will return true for all numbers not just prime numbers. I'll leave it up to you to spot the bug and the fix.
EDIT: No bug. See below comments.
Change your method to static and you can reference it without creating an instance of that class
public static boolean isprime(int n) {