Write a java program that reads the grades of 10 students, which is from 1 to 100, from the entrance, specifying that the scores of some people are from 90 to 100, some people are from 60 to 89 and some people are from 1 to 59. The program should print the average scores at the end. This is code for average, how can i add else and if or while to review how much numbers are in range 1 to 59 or 60 to 89 or 90 to 100?
import java.util.Scanner;
public class EhsanNp {
public EhsanNp() {
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new EhsanNp();
}
}
You can simply add three variables which store the number of grades between 1 to 59, 60 to 89 and 90 to 100 and increment them in the for loop. For example:
import java.util.Scanner;
public class EhsanNp {
int lowGrades;
int middleGrades;
int highGrades;
public EhsanNp() {
lowGrades = 0;
middleGrades = 0;
highGrades = 0;
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
if (Integer.parseInt(arr[i]) >= 1 && Integer.parseInt(arr[i]) <= 59) {
lowGrades++;
}
else if (Integer.parseInt(arr[i]) >= 60 && Integer.parseInt(arr[i]) <= 89) {
middleGrades++;
}
else {
highGrades++;
}
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new EhsanNp();
}
}
Then you can do whatever you want with the variables like displaying them for example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.