This program shows how to get input from a command line argument. In this program all possible error conditions are verified.
PROGRAM
class Prime
{
public static void main(String[] arg)
{
if (arg.length>0)
{
int n=Integer.parseInt(arg[0]);
int p=1,num,cnt;
if (n>0)
{
System.out.println("The first "+n+" prime numbers are");
cnt = 1;
System.out.println(2);
num=3;
while (cnt<n)
{
p=1;
for(int i=2;i<num;i++)
{
if (num%i == 0)
{
p=0;
break;
}
}
if (p==1)
{
System.out.println(num);
++cnt;
}
++num;
}
}
else
{
System.out.println("Enter a positive integer");
System.exit(0);
}
}
else
{
System.out.println("Enter a positive integer in the command line");
System.exit(0);
}
}
}
D:\Java\20CSC>java Prime 0
Enter a positive integer
D:\Java\20CSC>java Prime
Enter a positive integer in the command line
OUTPUT
D:\Java\20CSC>java Prime 5
The first 5 prime numbers are
2
3
5
7
11
D:\Java\20CSC>java Prime 10
The first 10 prime numbers are
2
3
5
7
11
13
17
19
23
29
D:\Java\20CSC>java Prime 1
The first 1 prime numbers are
2
D:\Java\20CSC>java Prime 2
The first 2 prime numbers are
2
3
D:\Java\20CSC>java Prime 3
The first 3 prime numbers are
2
3
5