javaexceptioninteger

Exception -- Exception in thread "main" java.util.InputMismatchException


i'm trying to find my very first steps in java and while developping the code below

import java.util.Scanner;

public class MoyEcart {

    public static void main(String[] args) {
        float moy= 0, ecart_type= 0, somme= 0, carre= 0, moy_tmp, part_one;
        Scanner sc= new Scanner(System.in);
        System.out.print("Dernier terme de la suite:");
        int n = sc.nextInt();

        float[] t= new float[n];
        for(int i=0; i<n; i++) {
            System.out.print("Terme " + i + ":");
            t[i] = sc.nextFloat();
        }

        for(int i=0; i<n; i++) {
            somme+= t[i];           
        }
        moy = somme/n;
        moy_tmp = moy * moy;

        for(int i=0;i<n;i++) {
            carre += t[i] * t[i];  
        }
        part_one = carre/n;
        ecart_type=(float) Math.sqrt(part_one - moy_tmp);
        System.out.println("Moyenne ="+moy);
        System.out.println("Ecart type="+ecart_type);
    }
}

I'm getting this error, and i couldn't find a solution to it, so please if you guys now a way out to this, i'll be grateful.

Exception in thread "main" java.util.InputMismatchException 
  at java.util.Scanner.throwFor(Scanner.java:864) 
  at java.util.Scanner.next(Scanner.java:1485) 
  at java.util.Scanner.nextFloat(Scanner.java:2345) 
  at MoyEcart.main(MoyEcart.java:17) 

Solution

  • I ran your code, and it works fine for me! You should first enter a single number and press enter. After that, you need to input that amount of numbers one at a time. This means you need to press enter after every number. The output I got from your program looks like this:

    Dernier terme de la suite:3
    Terme 0:1
    Terme 1:2
    Terme 2:3
    Moyenne =2.0
    Ecart type=0.8164965