Link to home
Start Free TrialLog in
Avatar of Sdot718
Sdot718

asked on

InputMismatch Exception

Trying to get scanner to read double values from a text file and I get this.

Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Scanner.java:840)
        at java.util.Scanner.next(Scanner.java:1461)
        at java.util.Scanner.nextDouble(Scanner.java:2387)
        at Array.main(Array.java:24)



public static void main(String[] args) throws FileNotFoundException

	{
		Scanner inFile = new Scanner(new FileReader("data"));

		double[] scores = new double[8];
		int index;

		for(index = 0; index < scores.length; index++)
		scores[index] = inFile.nextDouble();

Open in new window

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Please post the file called 'data'
Can all pieces in the file be interpreted as double?
Post your input, please
Avatar of Sdot718
Sdot718

ASKER

Data.Text posted in the code.
//Data.txt

Ashley Boyle 	8.2  8.0  9.2  4.6  8.3  8.9  7.0  9.5

Open in new window

the first two items cannnot be double
You need to get rid of everything other than the doubles
you need to skip the first tow with inFile.next()
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Do all of your lines follow exactly the same pattern?
A couple of points there:

a. the answer accepted doesn't read all the doubles
b. if you're going to have info in the file that is ignored, it would be more efficient to leave it out in the first place as i mentioned earlier
c. if you're determined to leave the string info in there for some reason, you'll find the following approach more flexible for mixed data:
public static void main(String[] args) throws FileNotFoundException {
        Scanner inFile = new Scanner(new FileReader("data"));

        double[] scores = new double[8];
        int index = 0;
	while(inFile.hasNext()) {
	    if(inFile.hasNextDouble()) {
		scores[index++] = inFile.nextDouble();
	    }
	    else {
		inFile.next();
	    }
	}
	System.out.println(Arrays.toString(scores)); // test
    }

Open in new window