2015-10-14 36 views
0

我想知道如何讓掃描儀可以在同一行上獲取所有不同的號碼。我的任務有要求我們計算年級平均值,他希望它是這樣的:從同一行獲取號碼

輸入等級的數量:5

輸入5個等級:95.6 98.25 89.5 90.75 91.56

的平均等級是93.13

我認爲掃描儀得到這些數字,它需要一個數組?但我們還沒有學到這些。任何幫助都是極好的!到目前爲止,我有:

// number of grades input 
    do { 
     System.out.println("Enter number of grades"); 
     // read user input and assign it to variable 
     if (input.hasNextInt()) { 
      numGrade = input.nextInt(); 
      // if user enters a negative grade will loop again 
      if (numGrade <= 0) { 
       System.out.println("Your number of grades needs to positive! Try again"); 
       continue; 
       // if grade number > 0 set loop to false and continue 
      } else { 
       cont = false; 

      } 
      // if user does not enter a number will loop again 
     } else { 
      System.out.println("You did not enter a number! Try again"); 
      // get the next input 
      input.next(); 
      continue; 
     } 
     // only not loop when boolean is false 
    } while (cont); 
    // user input of grades 
    do { 
     // prompt user to enter the grades 
     System.out.println("Enter the " + numGrade + " grades"); 
     // assign to input 
     if (input.hasNextDouble()) { 
      grades = input.nextDouble(); 
      // check if a grade is a negative number 
      if (grades <= 0) { 
       // report error to user and loop 
       System.out.println("Your grades needs to positive! Try again"); 
       continue; 
       // if user enter acceptable grades then break loop 
      } else { 
       cont2 = false; 
      } 
      // check if user entered a number 
     } else { 
      // if user did not enter number report error 
      System.out.println("You did not enter a number! Try again"); 
      input.next(); 
      continue; 
     } 
     // only not loop when boolean2 is false 
    } while (cont2); 

    // average calculation 
    average = grades/numGrade; 
    System.out.println(average); 

} 
+0

'nextInt','next','nextDouble'等都查找同一行上的下一個標記,如果當前行中沒有標記,只會查看下一行。 – RealSkeptic

回答

0

我想在你的作業分離的空間意味着你應該存儲在特定位置或變量中的每個號碼。

例如: 輸入三個編號:1 2 3

int number1 = input.nextInt(); 
int number2 = input.nextInt(); 
int number3 = input.nextInt(); 

現在掃描器將由nextInt()方法讀出。如果它讀取空間,那麼將完成該變量的保存值。

另一示例讀數組元素:

輸入三個編號:1 2 3

int[] myArray = new int[3]; 
for(int i = 0; i < myArray.length; i++){ 
    myArray[i] = input.nextInt(); 
} 

。注意,循環運行的3倍的陣列的長度。 也請注意在代碼中輸入Scanner類的引用,但我沒有聲明它。

+0

謝謝!我有點用兩個! –

3

我建議這個

// separates the line you send by spaces if you send the next line 
// 95.6 98.25 89.5 90.75 91.56 it will create an array like this 
// {"95.6","98.25", "89.5","90.75", "91.56"} 
String []grades = input.nextLine().split(' '); 
double total=0; 
for(int i=0;i<grades.length;i++){ 
    //parse each value to double and adds it to total 
    total+=Double.parseDouble(grades[i]); 

} 
double average= total/grades.length;