Reputation: 65
I am trying to introduce in a float array a set of float numbers:
protected float[] a = new float [100];
public void setCoef(){
System.out.println("Introduceti coeficientii: ");
for (int i = 0; i <= this.grad; i++)
{
Scanner in = new Scanner(System.in);
this.a[i] = in.nextFloat();
}
}
but It generates this exception when I input 2.3 for example:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextFloat(Scanner.java:2388)
at polinom.PolinomR.setCoef(PolinomR.java:35)
at polinom.PolinomReal.grade_coef(PolinomReal.java:14)
at polinom.Operatii.main(Operatii.java:43)
Upvotes: 0
Views: 3116
Reputation: 491
You should be checking if the value of your input can be interpreted as a float. Try using hasNextFloat()
to validate the value before you try to consume it. I don't know what you want to do if you encounter a bad value, but that will manage to avoid the exception.
You can use something like the following:
protected float[] a = new float [100];
public void setCoef(){
System.out.println("Introduceti coeficientii: ");
Scanner in = new Scanner(System.in);
for (int i = 0; i <= this.grad; i++)
{
while (!in.hasNextFloat())
{
// Do something with bad value, e.g.
// System.out.println("Bad value");
// in.nextLine();
}
this.a[i] = in.nextFloat();
}
}
Also, I'm not sure what this.grad
is, but you should either make sure it is less than the size of a
or add that to the check in the for loop.
Upvotes: 1
Reputation: 95978
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
You're getting this exception because you're trying to insert wrong values.
Make sure you're inserting 2.3
and not 2,3
or something other than numbers.
Your program should run with no problems if you enter 2.3
Upvotes: 2