How to sort an array and display it? [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
Here is my code:
package project4;
import java.util.Scanner;
public class ScoreAnalyzer {
//#OfScores is the length of the scores array
public static int numberOfScores = 0;
public static double[] scores = new double[numberOfScores];
public static double sum = 0.0;
public static double place = 0.0;
//Of sorted list
public static double[] sortedList = new double[numberOfScores];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of scores you'd like to average: ");
numberOfScores = input.nextInt();
scores = new double[numberOfScores];
for (int count = 0; count < scores.length; count++) {
System.out.print("Enter score #" + count + ": ");
place = input.nextDouble();
scores[count] = place;
System.out.println("The score of " + scores[count] + " is " + getGrade(count));
}
sumOfScores();
System.out.println("The average of these scores is: " + averageOfScores());
sort();
System.out.println("The sorted list of scores (above average scores are "
+ "marked with an\n" + "asterisk '*'): " + sortedList[numberOfScores]);
}
public static char getGrade(int i) {
//this
if (scores[i] >= 90.0) {
return 'A';
}
if (scores[i] >= 80.0) {
return 'B';
}
if (scores[i] >= 70.0) {
return 'C';
}
if (scores[i] >= 60.0) {
return 'D';
}
else {
return 'F';
}
}
public static double sumOfScores() {
//sum = 0.0;
for (int i = 0; i < numberOfScores; i++) {
sum += scores[i];
}
return sum;
}
public static double averageOfScores() {
double average = sum / numberOfScores;
return average;
}
public static void sort() {
for (int i = 0; i < scores.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = scores[i];
int currentMinIndex;
currentMinIndex = i;
for (int j = i + 1; j < scores.length; j++) {
if (currentMin > scores[j]) {
currentMin = scores[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
sortedList[currentMinIndex] = scores[i];
scores[i] = currentMin;
}
}
}
}
The program's purpose is to prompt the user for the number of scores to be entered first, then allow the user to enter that number of scores. As each score is entered, the program should give them a grade for each score inputted. The program then should use a method to find the sum, pass that sum into a method that finds the average, and sort the array in a method.The sorted array should be displayed along with the average and each score which is above the average should be noted with an asterisk beside it.
When I run the program, I am able to enter the number of scores I want to average, input those scores, obtain the sum and average but I'm having problem sorting it to have the asterisk to above average numbers:
Enter the number of scores you'd like to average: 3
Enter score #0: 90
The score of 90.0 is A
Enter score #1: 80
The score of 80.0 is B
Enter score #2: 70
The score of 70.0 is C
The average of these scores is: 80.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at project4.ScoreAnalyzer.sort(ScoreAnalyzer.java:86)
at project4.ScoreAnalyzer.main(ScoreAnalyzer.java:32)

There is a problem with the terminating condition of your for loop. Since the array index starts with 0, the highest index will go up to 2 for an array of size 3. However, count, using which you are accessing elements of scores[], is going up to 3 in your for loop and that is the reason for the ArrayOutOfBoundsException. Change the for loop as follows:
for (int count = 0; count < scores.length ; count++)

Related

Java - print user input of 4 integers, and the lowest, highest and average number

This program is supposed to take user input of four grades, take these grades and calculate the lowest, highest and average of them. Then it needs to print out the four grades along with the lowest, highest, and average of them with proper labels. I cannot figure out how to print out the four grades with my code, and for some reason it prints out the lowest, highest and average after every iteration of the loop, or every user input.
Here is what I have so far:
public class Test2 {
double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;
public void Test2 (double[] grades){
//Loop through all of the grades.
for(int i = 0; i < 4; i++){
double grade = grades[i];
//Add the grade to the total
total += grade;
//If this is the highest grade we've encountered, set as the max.
if(max < grade){
max = grade;
}
//If this is the lowest grade we've encountered, set as min.
if(min > grade){
min = grade;
}
}
System.out.println("Average is: " + (total / 4));
System.out.println("Max is: " + max);
System.out.println("Min is: " + min); }
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] grades = new double[4];
System.out.println("Please enter number");
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextDouble();
Test2 g = new Test2();
g.Test2(grades);
} } }
Can anyone help me with this? I need it to print out the four grades (user input), along withe the lowest, highest and average grade from the four grades, but ONLY ONCE, not after every iteration of the loop. Sorry if my code looks bad.
You have to call the method Test2(double grade) only once in the main method as there is a for loop inside Test2 method. I.e call Test2 method in main outside for loop.
Your answer should be the below class.
import java.util.Scanner;
public class Test2 {
double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;
public void doOperations(double[] grades) {
for (int i = 0; i < 4; i++) {
double grade = grades[i];
//Add the grade to the total
total += grade;
//If this is the highest grade we've encountered, set as the max.
if (max < grade) {
max = grade;
}
//If this is the lowest grade we've encountered, set as min.
if (min > grade) {
min = grade;
}
}
System.out.println("Average is: " + (total / 4));
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] grades = new double[4];
System.out.println("Please enter number");
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextDouble();
}
Test2 test2 = new Test2();
test2.doOperations(grades);
}
}

How can I get my user inputted numbers to be read all on one line to be placed into a 2D array?

Basically, I have this program. It is not completed yet but the gist of it is that it is a grade book with user input grades for a number of students they enter. They also enter the number of grades. What I'm struggling with is how to get the program to read the numbers after the first one on the line. The numbers being read is under the name "scores". So I want it to read it as:
1 2 3 4 (it just would read 1 and 5 right now)
5 6 7 8 (I want it to read them all)
Here's my code if it helps:
import java.util.Scanner;
import java.text.DecimalFormat;
public class SeventhAssignment {
public static double scores[][];
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(".00");
Scanner input = new Scanner(System.in);
int students;
System.out.print("Enter number of students");
students = input.nextInt();
if (students <= 0) {
System.out.println("Both numbers must be positive");
System.exit(0);
}
int grades;
System.out.print("Enter number of grades");
grades = input.nextInt();
if (grades <= 0) {
System.out.println("Both numbers must be positive");
System.exit(0);
}
double[][] arr = new double[students][grades];
System.out.println("Enter " + students * grades + " grades: ");
int i;
int j;
for (i = 0; i < students; i++) {
for (j = 0; j < grades; j++) {
Scanner scores = new Scanner(System.in);
arr[i][j] = scores.nextInt();
}
for (i = 0; i < students; i++) {
for (j = 0; j < grades; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
public double getMinimum() {
double lowGrade = scores[0][0];
for (double studentGrades[] : scores) {
for (double grade : studentGrades) {
if (grade < lowGrade)
lowGrade = grade;
}
}
return lowGrade;
}
public double getMaximum() {
double highGrade = scores[0][0];
for (double studentGrades[] : scores) {
for (double grade : studentGrades) {// if grade is greater than
// higherGrade, assign to higher
// grade
if (grade > highGrade)
highGrade = grade;
}
}
return highGrade;// returtn higher grade
}
public static double getAverage(double setofGrades[]) {
double total = 0;// Initializing total
// sum of grade for one student
for (double grade : setofGrades)
total += grade;
// return average of grade
return (double) total / setofGrades.length;
}
public void outputGrades() {
System.out.println("The grades are:\n");
System.out.println(" ");// for alignment
for (double test = 0; test < scores[0].length; test++)
System.out.printf("Test %d", test + 1);
System.out.println("Average"); // student average column heading
for (double student = 0; student < scores.length; student++) {
System.out.printf("student %2d", student + 1);
for (double test : scores[(int) student])// output student grades
System.out.printf("%8d", test);
// call method getAverage to calculate students average grade
// pass row of grades as the argument to getAveerage
double average = getAverage(scores[(int) student]);
System.out.printf("%9.2f\n", average);
}
}
}
Thanks ahead for any help you guys can bring!

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

Java program calculates averages. How do I display highest average?

I have a java program that takes the scores of 4 players and computes each player's average score when -1 is inputted. At the end of the program I need to display the highest average score out of the 4 averages, however I cannot figure out how to do this, can you guys set me in the right direction? The program looks like this when it is run: (I have also attached my code) I cannot use anything but loops.
Player 1
Enter your score: 100
Enter your score: 90
Enter your score: 80
Enter your score: 70
Enter your score: -1 (when -1 is inputted, the average score is calculated)
Average Score = 85.00
Player 2
Enter your score: 90
Enter your score: 90
etc.
etc.
import java.util.Scanner;
public class BowlingScores
{
public static void main(String[]args)
{
double score = 0;
double totalScore = 0;
double count = 0;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++){
System.out.printf("\nPlayer %d\n", player);
do{
System.out.println("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
} while (score != -1);
if (score == -1){
count--;
System.out.printf("Average Score = %.2f\n",totalScore/count);
count = 0;
score = 0;
totalScore = 0;
}
}
}
}
Just keep track of the highest average in another variable. Then in your score == -1 condition check to see if the current average is higher than the highest average, and if so make current the new highest. Then after your for loop you could print out the highest average.
You can add a copy of the highest at the top of your code like this double highest = 0 then in your for loop have a way to replace it if the current average is higher.
if(score > highest){
highest=score;
}
Then at the -1 you can either reset it to 0 or keep it going.
public static void main(String[] args) {
final List<Double> allAverages = new ArrayList<>();
double score = 0;
double totalScore = 0;
double avg = 0;
int count = -1;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++) {
System.out.printf("\nPlayer %d\n", player);
do {
System.out.println("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
} while (score != -1);
avg = totalScore / count;
System.out.printf("Average Score = %.2f\n", avg);
allAverages.add(totalScore / count);
score = 0;
totalScore = 0;
count = -1;
}
System.out.println("The highest is : " + Collections.max(allAverages));
}
Here a list of the modifications I did to your code to get it working :
The variable count now start at -1, so there is no need to do count-- when we exit the loop.
I've added a List that keep a track of all the averages.
I've removed the validation if(count == -1) after the loop as the only way to exit the loop is to have count == -1 so we already know it is the actual value.
To retrieve the maximum of all averages, I use Collections.max(allAverages).
Take average of all 4 players and store into one array. Then check for the largest number in array.
double[] highest = new double[4];
for(int i=0; i<4; i++){
highest[i] = totalScore/count;
}
if(highest[0]>highest[1] && highest[0]>highest[2] && highest[0]>highest[3])
System.out.println("highest" + highest[0]);
else if(highest[1]>highest[0] && highest[1]>highest[2] && highest[0]>highest[3])
System.out.println("highest" + highest[1]);
else if(highest[2]>highest[0] && highest[2]>highest[1] && highest[0]>highest[3])
System.out.println("highest" + highest[2]);
else System.out.println("highest" + highest[3]);
public static void main(String[]args) {
double bestScore = 0;
int bestPlayer = 1;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++){
System.out.printf("\nPlayer %d\n", player);
int count = 0; // does not need to be double
double totalScore = 0;
do {
System.out.println("Enter Your Score: ");
double score = input.nextDouble();
if (score != -1) {
totalScore += score;
count++;
}
} while (score != -1);
double averageScore = totalScore / count;
if (averageScore > bestScore) {
bestScore = averageScore;
bestPlayer = player;
}
System.out.printf("Average Score = %.2f\n", averageScore);
}
System.out.printf("Best Average Score = %.2f, best player = %d\n", bestScore, bestPlayer);
}
Just keep a variable to record the top average score every time as in topAverage in my example below. The code is same as your's except I changed the variable names for my readability.
public static void main(String[] args) throws NumberFormatException,
IOException {
double currentScore = 0;
double totalScore = 0;
int numScores = 0;
double averageScore = 0;
double topAverage = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 4; i++) {
do {
System.out.println("Enter Score");
currentScore = Double.parseDouble(br.readLine());
totalScore = totalScore + currentScore;
numScores += 1;
} while (currentScore != -1);
numScores-=1;
totalScore+=1;
averageScore = totalScore / numScores;
System.out.println("Average Score is " + averageScore);
if (topAverage < averageScore) {
topAverage = averageScore;
}
currentScore = 0;
totalScore = 0;
numScores = 0;
}
System.out.println("Top Average is " + topAverage);
}
Edit
#Andrei Nikolaenko posted the same answer before me, so consider that answer, I am adding this edit because I want to mention that my browser did not refresh on time to show me that the answer has already been posted.

The code compiles, but all my answers come out to be 0

The code compiles, but all my answers come out to be 0.
import java.util.Scanner;// use the Scanner class located in the "java.util" directory
public class Assignment2
{
public static void main(String[] args)//main method that runs the program using methods below
{
double[] numbers = new double[100];
Scanner input = new Scanner(System.in);
int count;
int c=0;
do
{
count = input.nextInt();
c++;
} while (count != 0 && c < numbers.length);
double min = findMin(numbers, numbers.length);
int countNeg = countNegative(numbers, numbers.length);
double sum = computePositiveSum(numbers, numbers.length);
System.out.println("The minimum number is " +min);
System.out.println("The sum of the positive numbers is $" +countNeg) ;
System.out.println("The total number of negative numbers is " +sum);
}
public static double findMin(double[] numbers, int count) //finds and displays the minimum input value
{
double min = numbers[0];
for(count =1; count<numbers.length; count++)
{
if(numbers[count] <min)
{
min = numbers[count];
}
}
return min;
}
public static int countNegative (double[] numbers, int count) //counts the number of times a negative number is added to the array
{
int countNeg =0;
for (count = 0; count < numbers.length; count++)
{
if(numbers[count] < 0)
{
countNeg = countNeg + 1;
}
}
return countNeg;
}
public static double computePositiveSum(double[] numbers, int count)//calculates the sum of the positive integers in the array
{
double sum = 0;
for(count=0; count<numbers.length; count++)
{
if(numbers[count] > 0)
{
sum = sum + numbers[count];
}
}
return sum;
}
}
You are not assigning the entered values to the array numbers. Add this
numbers[c] = count;
inside the do-while loop:
do {
count = input.nextInt();
numbers[c] = count;
c++;
} while (count != 0 && c < numbers.length);
Note that if you just input positive (> 0) numbers and don't fill the whole array numbers, findMin() will return 0, because it is the default value for the elements of the array.
Edit:
I would say that the print statement
System.out.println("The sum of the positive numbers is $" + countNeg);
System.out.println("The total number of negative numbers is " + sum);
are not coherent with the methods called. It should be:
System.out.println("The sum of the positive numbers is " + sum);
System.out.println("The total number of negative numbers is " + countNeg);
double[] numbers = new double[100];
Scanner input = new Scanner(System.in);
int count;
int c=0;
do
{
count = input.nextDouble();
numbers[c] = count;
c++;
} while (count != 0 && c < numbers.length);
This code should work. You have to add the numbers to the array which you are entering through stdin
double[] numbers = new double[100];
Here you are initializing the array with all 0.0 elements. You want to take input int he array from stdin?
You don't put anything into numbers array so they are all 0. The corrected code is this:
do
{
numbers[c] = input.nextDouble();
c++;
} while (numbers[c] != 0 && c < numbers.length);

Categories