That is because "text.txt"
is not a number. Try:
Scanner input = new Scanner(new File("text.txt"));
Question
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?
La solution
That is because "text.txt"
is not a number. Try:
Scanner input = new Scanner(new File("text.txt"));
Autres conseils
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"