在我当前的项目中,我必须从输入文件中读取一些数字(第一个是系数,第二个是的指数(。由于某种原因,我在使用";Integer.parseInt";。有人知道为什么/如何解决这个问题吗?下面的当前代码。
错误消息:
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)
输入文件:
2 5
-4 3
1 1
-16 0
驱动程序:
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
您在一个while循环中跳过了两行,不要这样做。由于您一次扫描整行,所以在阅读后还需要拆分该行(空格为delim(。
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);
}
此外,扫描仪就像迭代器——一旦你在while循环中使用它,它就是"迭代器";使用";。要再次扫描文件,您需要在两个while循环之间再次创建它:
inFile = new Scanner(new File("input.txt"));
nextLine()
读取一行文本。因此它有这个名字。
你不想要一行文字;毕竟,1行包含2个整数。你只需要一个整数。
呼叫.nextInt()
(忘记Integer.parseInt
(。