I am working on an assignment that calls upon a text file to read numbers line by line.
If line 1 number is 1, it looks at line 2 number (ex, line 2 = 13), and uses OneNumber class file to do various methods (such as prime or not prime).
If next line number is 2, it uses the TwoNumber class file to do various methods (such as finding the greatest divisible number).
I seem to have an issue implementing the methods into my main application code. It is reading the numbers 1 & 2, but not using the methods from OneNumber or TwoNumber class files.
The text file being used contains the following numbers:
1
13
1
6
8
2
7
1
3
2
11
So should read line 1, run OneNumber, and check for prime on 13. Then reads line 3, runs OneNumber, checks 6 for prime, etc.... When it hits 2, it should run TwoNumber and check for great common factor.
When compiled it just goes:
1
1
2 is not prime
1
2 is not prime
End of file
I understand its because of how I have written my code in the main app, so my problem is I do not know what I have done wrong or in what order I should be placing code when creating my new object or or or or.... (dumbfounded)!!!
Here are the three files:
Main app code:
import java.util.Scanner;
import java.io.*;
import TwoNumber.TwoNumber;
import OneNumber.OneNumber;
public class Ch5Lab {
public static void main(String[] args) throws IOException
{
OneNumber object1;
TwoNumber object2;
int num1=0;
int num2=0;
//Creates scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the input filename
System.out.print("Enter the filename to open: ");
String filename = keyboard.nextLine();
//Open the file;
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
int number = inputFile.nextInt();
if (number == 1)
{
inputFile.hasNextInt();
object1 = new OneNumber(number);
OneNumber.isPrime(number);
System.out.println(number);
} else if (number == 2)
{
object2 = new TwoNumber();
TwoNumber.greatestCommonFactor(num1, num2);
System.out.println(number + " is not prime.");
}
}
//Close the file
inputFile.close();
System.out.println("End of file.");
}
}
OneNumber class:
package OneNumber;
public class OneNumber
{
static int value;
public OneNumber(int value1)
{
value = value1;
}
//checks whether an int is prime or not.
public static boolean isPrime(int n)
{
//check if n is a multiple of 2
if (n % 2 == 0) return false;
//if not, then just check the odds
for(int i = 3; i * i <= n; i += 2)
{
if(n % i == 0)
return false;
}
return true;
}
}
TwoNumber class:
package TwoNumber;
public class TwoNumber
{
public static int greatestCommonFactor(int a, int b)
{
if (b == 0)
return a;
else
return greatestCommonFactor(b, a % b);
}
}