asked 137k views
1 vote
Simplifying a program using arrays

Get into a group of at most 3 students (if you are taking the online version of this course, you can complete the exercise independently)

Decide with your group which program would like to simplify: Grades, RandomWinner, or CoolingCoffee

Have one person at the keyboard between the other two group members, so everyone can participate easily.

Put your group members’ names at the top of your program, as comments.

Use your group’s knowledge of arrays and loops to simplify and clean up the program as much as you can.

Make sure everyone in your group can explain every detail of what is going on.

Call me over to look at your work.

CLEAN THIS UP PLEASE

public class Grades {

public static void main(String[] args) {

ConsoleIO.printLine("What is the next grade?");

double grade1 = ConsoleIO.readDouble();

ConsoleIO.printLine("What is the next grade?");

double grade2 = ConsoleIO.readDouble();

ConsoleIO.printLine("What is the next grade?");

double grade3 = ConsoleIO.readDouble();

ConsoleIO.printLine("What is the next grade?");

double grade4 = ConsoleIO.readDouble();

ConsoleIO.printLine("What is the next grade?");

double grade5 = ConsoleIO.readDouble();

int improved = 0;

if (grade2 > grade1) {

improved++;

}

if (grade3 > grade2) {

improved++;

}

if (grade4 > grade3) {

improved++;

}

if (grade5 > grade4) {

improved++;

}

ConsoleIO.printLine("Grades improved " + improved + " times.");

}

}

asked
User TSG
by
7.6k points

1 Answer

5 votes

A simplified example of the given java program using an array and a loop is shown below:

import java.util.Scanner;

public class Grades {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Group members' names

// Member 1:

// Member 2:

// Member 3:

// Using an array to store grades

double[] grades = new double[5];

// Reading grades using a loop

for (int i = 0; i < grades.length; i++) {

System.out.println("Enter grade " + (i + 1) + ":");

grades[i] = scanner.nextDouble();

}

int improved = countImprovedGrades(grades);

System.out.println("Grades improved " + improved + " times.");

}

// Function to count the number of improved grades

private static int countImprovedGrades(double[] grades) {

int improved = 0;

// Checking for improved grades using a loop

for (int i = 1; i < grades.length; i++) {

if (grades[i] > grades[i - 1]) {

improved++;

}

}

return improved;

}

}

Therefore, the above code is one that uses an array to store grades, and a loop to input and process the grades.

The countImprovedGrades function is one that checks for improved grades using a loop.

answered
User Robtot
by
7.6k points

No related questions found