我一直在努力学习扫描仪课程。我似乎无法用它来解释它的方法。我正在尝试运行一组似乎对我来说正确的代码。我尝试了一些调整但仍然没有。我收到此错误的任何提示
“线程中的异常”主“java.util.InputMismatchException at java.util.Scanner.throwFor(未知来源)at java.util.Scanner.next(未知来源)at java.util.Scanner.nextInt(未知来源)at java.util.Scanner.nextInt(未知来源)at PolynomialTest.main(PolynomialTest.java:18)“
public class PolynomialTest {
public static void main(String[] args) throws IOException {
Scanner fileData = new Scanner(new File("operations.txt"));
Polynomial math = new Polynomial();
int coeff = fileData.nextInt();
int expo = fileData.nextInt();
while (fileData.hasNext()) {
Scanner nextTerm = new Scanner(fileData.nextLine());
if (nextTerm.next().equalsIgnoreCase("insert")) {
math.insert(coeff, expo);
System.out.println("The term (" + coeff + ", " + expo
+ ") has been added to the list in its proper place");
System.out.println("The list is now: " + math.toString());
} else if (nextTerm.next().equalsIgnoreCase("delete")) {
math.delete(coeff, expo);
System.out.println("The following term has been removed ("
+ coeff + ", " + expo + ")");
System.out.println("The list is now: " + math.toString());
} else if (nextTerm.next().equalsIgnoreCase("reverse")) {
math.reverse();
System.out
.println("The list was reversed in order and the list is now: "
+ math.toString());
} else if (nextTerm.next().equalsIgnoreCase("product")) {
System.out.println("The product of the polynomial is: "
+ math.product());
} else {
System.out.println("Not a recognized input method");
}
nextTerm.close();
}
PrintWriter save = new PrintWriter("operations.txt");
save.close();
fileData.close();
}
答案 0 :(得分:1)
您的代码存在许多问题。在nextLine()
之后从未致电while(hasNext())
。您的while
循环应为
while (fileData.hasNextLine()) {
Scanner nextTerm = new Scanner(fileData.nextLine());
您在每个nextTerm.next()
声明中致电if-else
。您应该分配一个名为operation的String
变量。
String operation=nextTerm.next();
if (operation.equalsIgnoreCase("insert")) {
....
} else if (operation.equalsIgnoreCase("delete")) {
..........
}
...
else if (operation.equalsIgnoreCase("product")) {
.....
}
答案 1 :(得分:1)
扫描程序抛出InputMismatchException以指示检索到的标记与预期类型的模式不匹配,或者标记超出预期类型的范围。
int coeff = fileData.nextInt();
int expo = fileData.nextInt();
尝试将上面的内容更改为如下所示。(如果您在2个单独的行中有前2个整数输入,否则在使用fileData.nextLine().split(" ")
读取它们之后尝试解析它们)
int coeff = Integer.parseInt(fileData.nextLine());
int expo = Integer.parseInt(fileData.nextLine());
如果同一行中有2个整数
String s[] = fileData.nextLine().split(" ");
int coeff = Integer.parseInt(s[0]);
int expo = Integer.parseInt(s[1]);
如果您也可以发布Polynomial
课程,那就太好了。