Patti
Posts: 46
Nickname: patti
Registered: Feb, 2002
Still trying to get help
Posted: Apr 20, 2002 9:41 AM
Advertisement
Trying to get greatest common divisor with recursive method, reading from text file. can't get this to work. Please help.import NumberItem;
import DivisorCalc;
import java.util.StringTokenizer;
import java.io.*;
public class GcdDriver {
public static void main(String args[]) {
final int MAX = 4;
NumberItem[] items = new NumberItem[MAX];
StringTokenizer tokenizer;
String line,file = "numbers.txt" ;
int num1, num2, answer;
int count = 0;
try {
FileReader fr = new FileReader (file);
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
while (line != null ){
tokenizer = new StringTokenizer (line);
try
{
num1 = Integer.parseInt (tokenizer.nextToken());
num2 = Integer.parseInt (tokenizer.nextToken());
items[count++] = new NumberItem (num1, num2);
}
catch (NumberFormatException exception)
{
System.out.println ("Error in input. Line ignored:" );
System.out.println (line);
}
line = inFile.readLine();
}
inFile.close();
for (int scan = 0; scan < count; scan++)
System.out.println (items[scan]);
}
catch (IOException exception)
{
System.out.println (exception);
}
DivisorCalc.Gcd ();
}
} // class GcdDriver
import java.io.*;
public class DivisorCalc {
private static int dividend1, dividend2, num1, num2, number1, number2;
private static int max, answer, result;
public void NumberItem (int number1, int number2) {
num1 = number1;
num2 = number2;
}
public static int Gcd (int num1, int num2) {
if (num1 > num2) // to figure larger of the two numbers
max = num1;
else
max = num2;
while (dividend1 != dividend2) {
for ( int i = 1; i < max; i++)
dividend1 = num1 - max;
dividend2 = num2 - max;
max--;
if (dividend1 == dividend2)
answer = dividend1;
System.out.println ("Greatest common divisor: " + answer);
}
return answer;
} //class Gcd
} // class DivisorCalc
public class NumberItem {
private int num1, num2;
public NumberItem (int number1, int number2) {
num1 = number1;
num2 = number2;
}
}
Text file is:
45 15
100 35
4 7
I love Lucy