In: Computer Science
Convert this code written in Python to Java:
# Definition of a function isprime().
def isprime(num):
count=2;
flag=0;
# Loop to check the divisors of a number.
while(count<num and flag==0):
if(num%count!=0):
# Put flag=0 if the number has no divisor.
flag=0
else:
# Put flag=1 if the number has divisor.
flag=1
# Increment the count.
count=count+1
# Return flag value.
return flag
# Intialize list.
list=[]
#Prompt the user to enter Start and end numbers.
st=int(input("Start number:"))
en=int(input("End number:"))
while(st>en):
print ("End number must be greater than start number. Try again.")
st=int(input("Start number:"))
en=int(input("End number:"))
while(st<0 or en<0):
print ("Start and end must be positive. Try again.")
st=int(input("Start number:"))
en=int(input("End number:"))
while(st<=en):
# Call the function.
a = isprime(st);
if(a==0):
# Append the prime number to a list.
list.append(st)
st=st+1
for i in range(0, len(list), 10):
# Print 10 numbers per line.
print(*list[i:i + 10])
CODE:
import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int st,en,a,len=0,i;
//Prompt the user to enter Start and end
numbers.
System.out.print("Start number:");
st=input.nextInt();
System.out.print("End number:");
en=input.nextInt();
int list[]=new int[en];
while(st>en){
System.out.println("End number must be greater than start number.
Try again.");
System.out.print("Start number:");
st=input.nextInt();
System.out.print("End number:");
en=input.nextInt();
}
while(st<0 || en<0){
System.out.println("Start and end must be positive. Try
again.");
System.out.print("Start number:");
st=input.nextInt();
System.out.print("End number:");
en=input.nextInt();
}
while(st<=en){
// Call the function.
a = isprime(st);
if(a==0)
list[len++]=st; // Append the prime number to a list.
st=st+1;
}
for (i=0;i<len;i++){
//Print 10 numbers per line.
System.out.printf("%d ",list[i]);
if(i%10==9)
System.out.println();
}
}
//Definition of a function isprime().
public static int isprime(int num){
int count=2,flag=0;
// Loop to check the divisors of a number.
while(count<num && flag==0){
if(num%count!=0) // Put flag=0 if the number has no divisor.
flag=0;
else // Put flag=1 if the number has divisor.
flag=1;
count=count+1; // Increment the count.
}
return flag; // Return flag value.
}
}
OUTPUT: