Rainfall program not accepted in codeLab - java

I am working on an assignment from MyProrammingLab:
Write a RainFall class that has the following field:
• an array of doubles that stores the rainfall for each of the 12 months of
the year (where the first index corresponds with January, the second with
February, etc.)
The class should also have the following methods :
• a method that returns the total rainfall for the entire year
• a method that returns the average monthly rainfall for the year
• a method that returns the month with the most rain as a string
• a method that returns the month with the least rain as a string
Demonstrate the class in a program that takes 12 doubles from the user (take the
doubles in the order of the months of the year, the first corresponding to the
rainfall in January, etc.). Do input validation: if the user inputs a negative
number, ignore it and continue asking them for input until you have 12
nonnegative doubles .
Once the user has given you all 12 doubles , create an instance of the RainFall
class and call its methods , printing out the total rainfall, the average
monthly rainfall, the month with the most rain, and the month with the least
rain, each on a separate line.
Here is my program, which is working fine with netbeans but rejected by codeLab:
import java.text.DateFormatSymbols;
import java.util.Scanner;
public class RainFall {
final private double[] rainFall;
public RainFall(double[] arr) {
rainFall = arr;
}
public double getTotalRain() {
double total = 0;
for(int i=0;i<rainFall.length;i++)
total = total + rainFall[i];
return total;
}
public double getAverageRain() {
double average = 0;
for(int i=0;i<rainFall.length;i++)
average = average + rainFall[i];
return average/rainFall.length;
}
public String getHighestRain() {
int j=0;
for(int i=0;i<12;i++)
if(rainFall[i]>rainFall[j])
j=i;
return new DateFormatSymbols().getMonths()[j];
}
public String getLowestRain() {
int j=1;
for(int i=0;i<12;i++)
if(rainFall[i]<rainFall[j])
j=i;
return new DateFormatSymbols().getMonths()[j];
}
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
double[] rainfallInput = new double[12];
for(int i=1;i<=12;i++) {
System.out.print("Enter rainfall for month " + i + ":");
rainfallInput[i-1]=myScan.nextDouble();
myScan.nextLine();
if(rainfallInput[i-1]<0) {
System.out.print("Enter rainfall for month " + i + :");
rainfallInput[i-1]=myScan.nextDouble();
myScan.nextLine();
}
}
RainFall rain = new RainFall(rainfallInput);
System.out.println(rain.getTotalRain());
System.out.println(rain.getAverageRain());
System.out.println(rain.getHighestRain());
System.out.println(rain.getLowestRain());
}
}
Any help would be appreciated!
Thank you in advance

I'm assuming your answer is rejected because you can eventually input a negative number at the second rainfallInput[i-1]=myScan.nextDouble();
Try with a do-while loop instead to continuously ask for a positive number.
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
double[] rainfallInput = new double[12];
for (int i = 0; i < 12; i++) {
double input;
do {
System.out.print("Enter rainfall for month " + (i + 1) + ":");
input = myScan.nextDouble();
myScan.nextLine();
// Optionally tell why you are repeating input
/*
if (input <= 0) {
System.out.println("You must enter a positive value");
}
*/
} while (input <= 0);
rainfallInput[i] = input;
}
RainFall rain = new RainFall(rainfallInput);
System.out.println(rain.getTotalRain());
System.out.println(rain.getAverageRain());
System.out.println(rain.getHighestRain());
System.out.println(rain.getLowestRain());
}
public double getTotalRain() {
double total = 0;
for (int i = 0; i < rainFall.length; i++) {
total += rainFall[i];
}
return total;
}
public double getAverageRain() {
return getTotalRain() / (1.0 * rainFall.length);
}
public String getHighestRain() {
double max = Double.MIN_VALUE;
int maxIndex = 0;
for (int i = 0; i < rainFall.length; i++) {
double amount = rainFall[i];
if (amount > max) {
max = amount;
maxIndex = i;
}
}
return DateFormatSymbols.getInstance().getMonths()[maxIndex];
}
public String getLowestRain() {
double min = Double.MAX_VALUE;
int minIndex = 0;
for (int i = 0; i < rainFall.length; i++) {
double amount = rainFall[i];
if (amount < min) {
min = amount;
minIndex = i;
}
}
return DateFormatSymbols.getInstance().getMonths()[minIndex];
}

Get rid of myScan.nextLine(); in the for loop and code lab will accept it.

Related

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

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++)

Print out Average in for loop

This is my question
get to input a positive integer representing a number of weeks, loop
continuously until the value entered is positive. For each week, enter
a value for liters and a value for kilometers. For each value, should
loop until the value entered is positive. both values is a real
number. Then output the fuel economy for that week (liters divided by
kilometers). Finally, output the average fuel economy. You must make
good use of submodules in your answer.
This is my work
import java.util.*;
public class Exam8 {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (true) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum = result + (double)count;
System.out.println(result);
}
//average = getAverg(sum,count);
System.out.print("Average of fuel economy is: " + average);
}
public static double getAverg(double sum, int count) {
double average;
average = sum/count;
return average;
}
}
I get a problem when input value of lit and km, for example, I like to stop when to put either of a value of lit or km. Then I have another problem with outputting an average of the result (lit/km).
This code should work:
import java.util.*;
public class App {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (count < numweek) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum += result;
System.out.println(result);
}
System.out.print("Average of fuel economy is: " + getAverg(sum, numweek));
}
public static double getAverg(double sum, double numOfWeeks) {
double average;
average = sum/numOfWeeks;
return average;
}
}
Your first error was that the condition in the while loop wasn't correct. In order for the loop to stop you need to specify proper conditions. If condition is true it will loop indefinetely or until you set break.
Your second error was that you didn't calculate the average correctly. You should have just taken the sum for every week and added it to the current sum(which is zero at the beggining), and then just divide that sum by number of weeks to get the average.
You also didn't use your getAverg function anywhere.

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!

Getting the lowest and highest value from integers without using arrays?

I'm trying to write a class which reads 5 integers from the user and returns the highest and lowest value back. This must be done using loops and without using arrays and Integer.MIN.Value/Integer.MAX.Value. I've already succeeded writing code that gets 5 integers from the user and returns the highest value but I just can't get both the highest and the lowest value returned in the same class.
Here is the code I mentioned above:
import java.util.Scanner;
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;
for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (number > max){
max = number;
}
}
System.out.println("Highest value: " + max);
}
}
here you go :)
import java.util.Scanner;
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int min = 0;
for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (x == 0 || number > max){
max = number;
}
if (x == 0 || number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}
Why not just repeat your max logic for min?
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Give me an integer: ");
number = input.nextInt();
int max = number;
int min = number;
for (int x = 0; x<4; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (number > max){
max = number;
}
if (number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}
Note that max and min are initially set to the first number that the user enters, so there will be no false 0's and no need to MAX_INT or MIN_INT. This in turn makes the loop run once less so terminate at i == 4 instead of 5.

Categories