Ok, so I have to write a program that takes a low and high number and an input filename from the command line and has to do the following three things:
1) Print all primes numbers in the range from low to high on a single line, separated by a space.
2) Print all perfect numbers in the range from low to high on a single line, separated by a space.
3) Echo the words from the input file and indicate if they are palindromes or not.
My code is as follows:
port java.io.*;
import java.util.*;
public class Program3
{
public static void main (String[] args)
{
try
{
int lo=0,hi=0; // range of #s to look for primes and perfects
String infileName; // file of Strings, one per line
BufferedReader infile = null;
if (args.length < 3)
{
System.out.println("CMD LINE INPUT ERROR: Must enter 2 numbers followed by name of input file on cmd line.");
System.exit(0);
}
lo=Integer.parseInt(args[0]);
hi=Integer.parseInt(args[1]);
infileName=(args[2]);
for(int n=lo; n<=hi; n++){
boolean isPrime = (n%2 != 0);
int divisor=3;
while(isPrime && divisor<n/2);
{
if(n%divisor==0)
isPrime=false;
else
divisor++;
if (isPrime)
System.out.print(n + " ");
System.out.println();
for (int perfectNum=lo; perfectNum<=hi; perfectNum++)
{
int total=0;
for (int perfectDiv=1 ; perfectDiv<perfectNum;perfectDiv++)
{
if (perfectNum % perfectDiv==0) total=total+perfectDiv;
}
if (perfectNum==total) System.out.print(perfectNum + " ");
}
}
String line=null;
BufferedReader bufferedReader = new BufferedReader(new FileReader(infileName));
while (infile.ready())
{
line = infile.readLine();
}
boolean isPalindrome=true;
int lineLength = line.length();
int middleOfline = lineLength/2;
for (int beginningLetter = 0; beginningLetter<middleOfline; beginningLetter++ )
{
if (line.charAt(beginningLetter) != line.charAt(lineLength-beginningLetter-1))
{
isPalindrome=false;
}
if (isPalindrome)
System.out.println( line + " IS a palindrome." );
else
System.out.println( line + " NOT a palindrome." );
}
}
}
catch ( Exception e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("EXCEPTION CAUGHT: " + sw.toString() );
System.exit( 0 );
}
}
}
I'm getting a few problems. First of all, whenever I input any number greater than 7, my terminal only displays 1, 3, 5, and 7, but no other primes. My perfect number section is printing 6 and 28 multiple times instead of one on the same line, separated by a space. Finally, I'm not sure that my BufferedReader syntax is correct, and each time I attempt to execute the problem, it says that the file I am trying to read does not exist.
Any help or suggestions would be greatly appreciated!
Thanks,
Jay