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.InputMismatchExc eption
at java.util.Scanner.throwFor (Scanner.j ava:840)
at java.util.Scanner.next(Sca nner.java: 1461)
at java.util.Scanner.nextDoub le(Scanner .java:2387 )
at Array.main(Array.java:24)
Exception in thread "main" java.util.InputMismatchExc
at java.util.Scanner.throwFor
at java.util.Scanner.next(Sca
at java.util.Scanner.nextDoub
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();
Please post the file called 'data'
Can all pieces in the file be interpreted as double?
Post your input, please
Post your input, please
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:
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
}