2016-08-07 41 views
1

我有一個小問題。我需要讀一行中的兩個單詞來表示姓名和姓氏。二維數組,線程「main」中的異常java.util.InputMismatchException

public void Promedios5(){ 
    Scanner Marbis=new Scanner(System.in); 
    String[] x=new String[5]; 
    double[][] a=new double[5][4]; 
    double[] b=new double [5],c=new double[5]; 
    System.out.println("Este programa genera los promedios de las notas de cuatro unidades\n" 
      + "se le solicitarán a usted, el nombre y las cuatro notas"); 
    System.out.println("Podría ingresarlas ahora por favor:"); 
    for(int y=0;y<=4;y++){ 
     System.out.println("Ingrese el nombre:"); 
     x[y]=Marbis.nextLine(); 
     for(int z=0;z<=3;z++){ 
      a[y][z]=Marbis.nextDouble(); 
     } 
     b[y]=a[y][0]+a[y][1]+a[y][2]+a[y][3]; 
     c[y]=b[y]/4; 
    } 
    System.out.println("Ahora usted verá los promedios de las personas:"); 
    System.out.println("Nombre:\t\t\tPromedio"); 
    for(int m=0;m<=4;m++) 
     System.out.printf("%s:\t\t%.2f\n",x[m],c[m]); 
} 

在這裏,我有錯誤:x[y]=Marbis.nextLine();
我知道,我用它在一條線上兩個或多個單詞,但在第二次機會,它標誌着我的錯誤,像這樣的(這是結果,我認爲我可以在nextLine使用數組):

MArio Albert 
100 
100.00 
78.00 
100.00 
Ingrese el nombre: 
John Antoinie 
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.nextDouble(Scanner.java:2413) 
    at vectormarbis1.MarbisVectors2.Promedios5(MarbisVectors2.java:125) 
    at vectormarbis1.VectorMarbis1.main(VectorMarbis1.java:28) 
C:\Users\ManoloAurelio\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 
BUILD FAILED (total time: 39 seconds) 
+0

這是因爲你的'x [y] = Marbis.nextLine();'在你採用double值後將新的行字符作爲一個字符串。嘗試在獲取雙精度值後刷新輸入。 – VatsalSura

回答

0

你只flush Java中的輸出。

何時放棄剩下的行?爲了解決您的問題,您可以撥打

input.nextLine(); 

你需要像您期望從下一行讀做這個nextDouble()後。

我希望下面給出的代碼可以幫助你解決你的問題。

public void Promedios5(){ 
    Scanner Marbis=new Scanner(System.in); 
    String[] x=new String[5]; 
    double[][] a=new double[5][4]; 
    double[] b=new double [5],c=new double[5]; 
    System.out.println("Este programa genera los promedios de las notas de cuatro unidades\n" 
    + "se le solicitarán a usted, el nombre y las cuatro notas"); 
    System.out.println("Podría ingresarlas ahora por favor:"); 
    for(int y=0;y<=4;y++){ 
    System.out.println("Ingrese el nombre:"); 
    x[y]=Marbis.nextLine(); 
    for(int z=0;z<=3;z++){ 
     a[y][z]=Marbis.nextDouble(); 
    } 
    Marbis.nextLine(); //Just add this line here 
    b[y]=a[y][0]+a[y][1]+a[y][2]+a[y][3]; 
    c[y]=b[y]/4; 
    } 
    System.out.println("Ahora usted verá los promedios de las personas:"); 
    System.out.println("Nombre:\t\t\tPromedio"); 
    for(int m=0;m<=4;m++) 
    System.out.printf("%s:\t\t%.2f\n",x[m],c[m]); 
} 
相關問題