+ 1
Can someone tell whats wrong with this code
Can you find the mistake import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input= new Scanner(System.in); System.out.println("Enter a number"); int numb=input.nextInt(); for(int i=1;i<100;i++){ int count=0; while( numb%i==0){ count++ ;} return count ;} if(count==2){ System.out.println("A Prime Number");} else {System.out.println("Not a prime number");} input.close(); }}
4 Answers
+ 2
Just modify this part.
int count=0;
for(int i=1;i<=numb;i++){
if(numb%i==0){
count++ ;}
}
1) count is declared outside because you declared it inside for loop and it will have a scope limited to the loop and cannot be accessed outside.
2) Range should be set to i<=numb because if the number is 7, why would you want to check 7%99? You should check only till numb.
3) while loop should be an if statement.
4) you need not return the count.
+ 1
Thank you
0
- please do not write close parenthesis } at end of line
(with the exception of in-line notation)
- do not close standard input stream