문제

public class Test
{
    public static void main(String[] args) throws FileNotFoundException
    {
        Scanner input = new Scanner("text.txt");
        int x = input.nextInt();        
    }
}

text.txt being:

8 
8
6  
7

This code throws a InputMismatch Exception. Why?

도움이 되었습니까?

해결책

That is because "text.txt" is not a number. Try:

Scanner input = new Scanner(new File("text.txt"));

다른 팁

The constructor Scanner(String) accepts a String to read from, not a file name.

So, nextInt() is trying to read an int from the String you pass to it, ie. "text.txt".

Instead, use the constructor that accepts a File source, Scanner(File).

The problem is due to overloading. You are calling new Scanner(String) instead of new Scanner(File). If you tried scanner.next() you would see it returns "text.txt"

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top