当前位置: 首页 > 知识库问答 >
问题:

扫描程序类和线程“主”java.util.Input不匹配异常错误

石喜
2023-03-14

我一直在努力学习扫描仪课程。我就是无法理解它的方法。我试着运行一组对我来说正确的代码。我试着做了一些调整,但还是没用。我为什么会收到这个错误的任何提示

线程mainjava.util.InputMismatchExceptionjava.util.Scanner.throwFor(未知源)java.util.Scanner.next(未知源)java.util.Scanner.nextInt(未知源)java.util.Scanner.nextInt(未知源)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();

}

共有2个答案

艾骏喆
2023-03-14

扫描仪抛出InputMismatchException,以指示检索到的令牌与预期类型的模式不匹配,或者令牌超出预期类型的范围。

int coeff = fileData.nextInt();
int expo = fileData.nextInt();

试着把上面的改成下面的。(如果您的前两个整数输入在两个单独的行中,否则尝试在读取它们之后使用< code>fileData.nextLine()解析它们。拆分(" " )

int coeff  = Integer.parseInt(fileData.nextLine());
int expo = Integer.parseInt(fileData.nextLine());

如果同一行中有两个整数

    String s[] = fileData.nextLine().split(" ");
    int coeff   = Integer.parseInt(s[0]);
    int expo  = Integer.parseInt(s[1]);

很好,如果你可以发布你的<code>多项式

傅英喆
2023-03-14

您的代码存在许多问题。从未在 时有下一个)之后调用下一行()。。你的 while 循环应该是

while (fileData.hasNextLine()) {
   Scanner nextTerm = new Scanner(fileData.nextLine());

您调用了<code>nexterm。next()在每个<code>if-else字符串变量赋值

   String operation=nextTerm.next();

   if (operation.equalsIgnoreCase("insert")) {
      ....
   } else if (operation.equalsIgnoreCase("delete")) {
    ..........
   } 
   ...
   else if (operation.equalsIgnoreCase("product")) {
     .....
   } 
 类似资料: