Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this java code correct for the question? (Without arrays)

Tags:

java

The question is:

Write a java program to accept any 20 numbers and display only those numbers which are prime.

And my code is:

import java.io.*;
class primenumber
{
public static void main(String args[]) throws IOException
{
    InputStreamReader read = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(read);
    int i,j,n;
    int p = 0;
    for(i=1;i<=20;i++)
    {
        System.out.println("Enter a number");
        n = Integer.parseInt(in.readLine());
        p = 0;
        for(j=1;j<=n;j++)
        {
            if(n%j==0)
                p++;
        }
        if(p==2)
            System.out.println(n);
    }
}
}  

So is this correct?

like image 970
Code Learner Avatar asked Jul 12 '26 20:07

Code Learner


1 Answers

From what I can tell from reading your program it is correct: it does what the assignment says and without arrays.

Depending on the requirements in your class it may be argued that input validation is missing. If I enter -4, you program will not print it (which may be considered correct?), but if I enter 3.14 or apple, it will probably crash.

There are a couple of minor stilistic issues, but when you ask about correctness, the answer is yes, it is correct.

like image 107
Ole V.V. Avatar answered Jul 15 '26 09:07

Ole V.V.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!