I currently have a text file as follows:
3 5 6 9
3 4 6 7 2
3 5 7 2 5 3
The file when read into java should be displayed as 3x^5 + 6x^9. The second line would be read as 4x^4 + 6x^7 + 2. The cannot get my program to display this as I dont know how to convert these numbers into that form. I currently get just the numbers with spaces between them when i run the program.
Here is what I have attempted:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Driver {
public static void main(String[] args) {
try {
@SuppressWarnings("resource")
Scanner myfile = new Scanner(new File("poly.dat"));
Polynomial[] mypolynomial;
mypolynomial = new Polynomial[10];
int index = 0;
if (myfile.hasNext() == true) { //ignore this part
myfile.nextLine();
} else {
System.out.println("Error: File is empty");
return;
}
while (myfile.hasNextLine()) {
mypolynomial[index] = new Polynomial(myfile.nextLine());
index++;
}
String menu = "Please choose a Polynomial \n";
for (int i = 0; i < index; i++) {
menu = menu + i + " " + mypolynomial[i].getNumber() + "\n";
}
String choicemenu = "What do you want to do ? \n " + "A - Display a Polynomial \n "
+ "B - Add two Polynomial \n " + "C - Subtract two Polynoimal \n "
+ "D - Multiply two Polynomial \n ";
String action = JOptionPane.showInputDialog(choicemenu);
if (action.equals("A")) {
int choice = Integer.parseInt(JOptionPane.showInputDialog(menu));
JOptionPane.showMessageDialog(null, mypolynomial[choice]);
}
} catch (FileNotFoundException e) {
System.out.println(" OOOPS - something wrong - maybe the file name is wrong");
}
}
}
public class Polynomial { //Testing the program
String poly;
public Polynomial(String p)
{
poly = p;
}
public String getNumber() {
return poly;
}
public void setNumber(String p)
{
poly=p;
}
public String toString()
{
String result = "The Polynomial is " + poly;
return result;
}
}
I want to first display these digits as polynomials, then I eventually want to perform operations with them. Can anyone help me?