简体   繁体   English

为什么会出现输入不匹配异常?

[英]Why do I get Input Mismatch Exception?

I have this code and it's returning an InputMismatchException . 我有这段代码,它返回一个InputMismatchException But I don't understand why! 但是我不明白为什么! Here is the code: 这是代码:

import java.io.*;
import java.util.*;
import java.lang.*;

class Test
{
    public static void main(String a[])
    {
        Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
        ArrayList<String> arr = new ArrayList<String>();
        arr.add(scanner.next());
        int x = scanner.nextInt();
        Collections.sort(arr);
        String _converted = arr.toString();
        String smallest,largest;
        int l = _converted.length()-x;
        int s = _converted.length();
        smallest = _converted.substring(0,x);
        largest = _converted.substring(l,s);
        System.out.println(smallest);
        System.out.println(largest);
    }
}

The code is to sort an input string and then output the first n words and the last n words where n is another input integer. 代码是对输入字符串进行排序,然后输出前n个字和后n个字,其中n是另一个输入整数。

Here's the input: 这是输入:

welcometojava
3

and the error: 和错误:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at dd.main(dd.java:12)

An input mismatch exception comes from trying to read the wrong type. 输入不匹配异常来自尝试读取错误的类型。 Java is taking the number you're inputting and not reading it as an int. Java将您输入的数字作为一个整数而不是将其读取为整数。

I don't exactly how you're inputting, but in general, you use 我输入的方式不完全正确,但总的来说,

useDelimiter("\\n")

which is causing some oddities. 这引起了一些奇怪的事情。 I don't know why you have it. 我不知道你为什么拥有它。 I would just change that line to 我只是把那条线改成

Scanner scanner = new Scanner(System.in);

Java handles new lines by itself. Java自行处理新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM