Issue
On my current project I have to read some numbers (first is coefficient, second is the exponent there of) from an input file. For some reason I get an error for using "Integer.parseInt". Does anyone know why/how to fix this? Current code below.
Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "2 5 "
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at polynomialproject.Driver.main(Driver.java:35)
Java returned: 1
BUILD FAILED (total time: 0 seconds)
Input File:
2 5
-4 3
1 1
-16 0
Driver:
import java.io.*; //Can use all io's
import java.util.*; //Can use all util's
import polynomialproject.SortedLinkedList;
import polynomialproject.SortedListInterface;
public class Driver {
private static Scanner file;
static PrintWriter outputFilePrinter;
static Scanner inputFileScanner;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile;
PrintWriter printWriter = new PrintWriter("output.txt"); //printWriter will output to proper text
inFile = new Scanner(new File("input.txt"));
Polynomial One = new Polynomial();
while (inFile.hasNext()) {
String String1 = inFile.nextLine(); //Reads lines
int one = Integer.parseInt(String1);
String String2 = inFile.nextLine();
int two = Integer.parseInt(String2);
One.setTerm(two, one);
}
Polynomial Two = new Polynomial();
while (inFile.hasNext()){
String String1 = inFile.nextLine();
int one = Integer.parseInt(String1);
String String2 = inFile.nextLine();
int two = Integer.parseInt(String2);
One.setTerm(two, one);
}
printWriter.println(One.toString());
printWriter.println("The degree of the first polynomial is: " + One.getDegree());
printWriter.println("The coefficient of exponent two is: " + One.getCoefficient(2));
printWriter.println("The coefficient of exponent three is: " + One.getCoefficient(3));
printWriter.println("The degree of the second polynomial is: " + Two.getDegree());
printWriter.println("The sum of the polynomials is: " + Two.sum(Two));
printWriter.close();
}//End main
}//End Driver
Solution
You are skipping 2 lines in one while loop, don't do that. Since you are scanning whole row at once, you need to also split the row (with space as delim) after reading.
while (inFile.hasNext()) {
String line = inFile.nextLine();
String[] numbers = line.split(" ");
int one = Integer.parseInt(numbers[0]);
int two = Integer.parseInt(numbers[1]);
One.setTerm(two, one);
}
Also, a scanner is like iterator - once you use it in while loop, it is "used". To scan file again, you need to create it again, between your two while loops:
inFile = new Scanner(new File("input.txt"));
Answered By - Goddy