简体   繁体   中英

Why do I get Input Mismatch Exception?

I have this code and it's returning an 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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