我是 Stack Overflow 的新手,所以請放輕松:D
我在解決這個問題時遇到了一些問題,因為我的資料存盤在一個陣列中,我需要一種能夠將相同資料放入變數中的方法,因為我需要做一些操作來獲得平均分數,我嘗試做的第一件事是創建一個變數并將陣列作為值,但它不允許我做任何事情,我已經花了很多時間在它上面,但我仍然無法理解如何修復它,所以如果你能幫我解決這個問題。
所以總結一下我想要做的是獲取我存盤在 i 中的學生數量和應該在陣列 [i] 中的學生的百分比,這是為了獲得學生數量的平均分數,所以百分比總和 / 學生人數 * 100 = 平均分數百分比。
import java.util.Scanner;
公共類主{
public static void main(String[] args) {
System.out.println("Hello MJ ");
Scanner sc= new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i<studenti;i )
{
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i]= Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
for (int i=0; i<studenti;i )
{
System.out.println((array[i]) "%");
}
System.out.println("\nThe Average Score is: " average "%");
int average = (persentegesOfStudents)/students;6
}
uj5u.com熱心網友回復:
請注意,為了獲得平均值,您需要將分數相加,然后除以學生人數。您的第二個for回圈看起來是處理總和的正確位置,此外,您需要average在列印之前宣告變數。這是一些建議(請參閱我的評論):
public static void main(String args[]) {
System.out.println("Hello MJ ");
Scanner sc = new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i < studenti; i ) {
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i] = Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
int sum = 0; // Added a variable for sum
for (int i = 0; i < studenti; i ) {
System.out.println((array[i]) "%");
sum = array[i]; // maintaining sum
}
int average = sum / array.length; // calculating the average
System.out.println("\nThe Average Score is: " average "%");
}
請注意,如果將平均值用作浮點數而不是整數,則可以使平均值更準確。
uj5u.com熱心網友回復:
使用流處理資料。將您的陣列轉換為 intSream
IntStream stream = Arrays.stream(arr);
intSream 有很多函式,例如平均、最小值、最大值、總和等。

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465532.html
