I'm new to Stack Overflow So please go easy on me :D
I'm having some problems solving this problem, because of my data is stored inside of an array I need a way to be able to put the same data inside of a variable because I need to do some operation to get the average score, the first thing that I try to do was making a variable and giving it the array as the value but it was not allowing me to do anything, I've spent quite a lot of times on it and I still cannot like understand how to fix it, so if you could please help me out with this problem.
So to summarise what I'm trying to do is get the number of students that I have stored in i and the percentage Of the students that should be in array[i], this is to obtain the average score for the number of students, so the Sum Of Percentages / number of Students * 100 = Average Percentage of Score.
import java.util.Scanner;
public class main {
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
}
CodePudding user response:
Note that in order to get the average, you need to sum the scores, and then to divide by the number of students. Your second for
loop looks like the right place to handle the sum, and in addition you need to declare the average
variable before printing it. Here is some suggestion (see my comments):
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 "%");
}
Note that you can make the average more accurate if you work with it as float and not integer.
CodePudding user response:
Use a stream to process data. Convert your array to intSream
IntStream stream = Arrays.stream(arr);
intSream have many funtions like average, min , max, sum etc.