I need to write a program that stores the total rainfall for 12 months then show an output of the total, average, the month with the highest, and lowest rainfall. My program runs but but I don't know how to make the output the number of the month instead of the amount of rainfall in that month.
For example when I have, Enter rain fall for month 6: 15.6 My output should be 6 not 15.6. Thanks for your help.
import java.util.Scanner;
public class Rainfall
{
public static void main (String [] args)
{
double[] rain = new double[12]; // The rainfall data
getValues(rain);
showValues(rain);
System.out.println("The total rainfall for this year is: " + totalRain(rain));
System.out.println("The average rainfall for this year is: " + averageRain(rain));
System.out.println("The month with the highest amount of rain is: " + mostRain(rain));
System.out.println("The month with the lowest amount of rain is: " + leastRain(rain));
}
/**
showValues method
#param rain Display the rainfall array
*/
public static void showValues(double[] rain)
{
}
/**
getValues method
#return The rain array filled with user input
*/
public static void getValues(double[] array)
{
Scanner scan = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.println("Enter rain fall for month " + (i + 1) + ".");
array[i] = scan.nextDouble();
}
}
/**
getTotal method
#return The total of the elements in
the rainfall array.
*/
public static double totalRain(double[] rain)
{
double total = 0.0; // Accumulator
// Accumulate the sum of the elements
// in the rainfall array.
for (int index = 0; index < rain.length; index++)
//total += sales[index];
total = total + rain[index];
// Return the total.
return total;
}
/**
getAverage method
#return The average of the elements
in the rainfall array.
*/
public static double averageRain(double[] rain)
{
return totalRain(rain) / rain.length;
}
/**
getHighest method
#return The highest value stored
in the rainfall array.
*/
public static double mostRain(double[] rain)
{
double highest = rain[0];
for (int index = 1; index < rain.length; index++)
{
if (rain[index] > highest)
highest = rain[index];
}
return highest;
}
/**
getLowest method
#returns The lowest value stored
in the rainfall array.
*/
public static double leastRain(double[] rain)
{
double lowest = rain[0];
for (int index = 1; index < rain.length; index++)
{
if (rain[index] < lowest)
lowest = rain[index];
}
return lowest;
}
}
Here is a pretty simple method using JAVA 8 Streams:
Double[] doubles = new Double[12];
List<Double> doubleList = Arrays.asList(doubles);
Double max = doubleList.stream().mapToDouble(dub -> dub).max().getAsDouble();
Double min = doubleList.stream().mapToDouble(dub -> dub).min().getAsDouble();
Try this: Instead of the amount of rain at the given index, you'd want the index istelf.
public static double mostRain(double[] rain)
{
double highest = rain[0];
int highestMonth = 0;
for (int index = 1; index < rain.length; index++)
{
if (rain[index] > highest)
highest = rain[index];
highestMonth = index;
}
return highestMonth;
}
Related
The goal of this class is to be able to take input for rainfall totals from the user. After taking the input, the program will display rainfall totals for the year, average monthly rainfall, month with the most rain and month with the least rain. Here is my code:
import java.util.Scanner;
public class Rainfall {
private static final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
public static void main(String[] args){
Scanner input = new Scanner(System.in);
final int MONTHSINYEAR = 12;
double[] rainfall = new double[MONTHSINYEAR];
System.out.println("Enter the monthly rain fall amount: ");
int i = 0;
for (i = 0; i < MONTHSINYEAR; i++){
do {
System.out.println("Enter rainfall for month " + (i + 1) + ": ");
rainfall[i] = input.nextDouble();
}
while (rainfall[i] < 0);
}
System.out.println("The total rainfall for the year is: " + totalRainfall(rainfall));
System.out.println("The average monthly rainfall is: " + averageRainfall(rainfall));
System.out.println("The month with the most rain is: " + months[maxRainfall(rainfall)]);
System.out.println("The month with the least rain is: " + months[minRainfall(rainfall)]);
}
public static double totalRainfall(double[] arr){
double total = 0;
for (int i = 0; i < arr.length; i++){
total += arr[i];
}
return total;
}
public static double averageRainfall(double[] arr){
double average = 0;
average = totalRainfall(arr) / arr.length;
return average;
}
public static double maxRainfall(double[] arr){
double max = arr[0];
double maximum = 0;
for (int i = 0; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
maximum = i;
}
}
return maximum;
}
public static double minRainfall(double[] arr){
double min = arr[0];
double minimum = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] < min){
min = arr[i];
minimum = i;
}
}
return minimum;
}
}
When compiling, the following lines obtain an error that says "Possible lossy conversion from double to int":
System.out.println("The month with the most rain is: " + months[maxRainfall(rainfall)]);
System.out.println("The month with the least rain is: " + months[minRainfall(rainfall)]);
I am not sure of how to proceed. What should be changed so those two lines do not have errors?
Your method is returning a double, change it to an int (and the method signature) so that it is returning the index of the maximum value
public static int maxRainfall(double[] arr){
double max = arr[0];
int maximum = 0;
for (int i = 0; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
maximum = i;
}
}
return maximum;
}
the index to an array lookup expression (the idx in expressionOfTypeArray[idx]) must be of type int, but you're providing a double. What the error is trying to tell you is that perhaps that double could be, say, 5.5, or 2^100; both of these numbers have no equivalent int value. Maybe you analyse the code and conclude that this can't happen, but the compiler doesn't know this, so out of defensive principles it won't silently try to smash the square peg that is a double into the round hole that is an int just because that's the only thing that works here.
You could simply.. tell the compiler that, yeah, smash it in there: months[(int) maxRainfall(rainfall)]); - this will round the number by lopping off any fractional part, so, 5.5 becomes 5, silently.
But, I'd fix your methods. The maxRainfall method returns the index of the month when the max rainfall occurred. There is absolutely no reason whatsoever why that should be a double; there is, after all, no "5.5th month". Just make that public static int minRainfall(... and it'll work fine.
I am trying to create 3 methods which calculate the sum and average of a random array then outputting the result.
I am trying to get an output similar to -
java RandomArray 5
9 7 2 1 4
Sum: 23
Mean: 4.6
but I am getting "Usage: java RandomArray . Example: java RandomArray 5"
if you can spot the errors in my code and help with how to get this output.
public class RandomArray {
private int[] numbers; //instance variable
/**
* Constructor
*
*#param size The size of the array
*/
public RandomArray(int size){
numbers = new int[size];
for(int i=0; i<numbers.length;i++){
numbers[i] = (int)(Math.random()*10); // a random number between 0-9
}
}
/**
* a method to print the array elements
*/
public void printArray() {
for (int i = 0; i < numbers.length; i++)
System.out.print(i + " ");
}
/**
* A method to calculate the sum of all elements
*
*#return The sum
*/
public int calSum(){
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
/**
* A method to calculate the mean of all elements
*
*#return The mean
*/
public double calMean() {
int sum = calSum();
int length = numbers.length;
return (double) sum / length;
}
/**
* a method to print the array elements in reverse order
*/
public void printReverse(){
}
/**
* A main method to test
*/
public static void main(String[] args) {
// Check to see if the user has actually sent a paramter to the method
if (args.length != 1){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}
// Create an instance of the class
RandomArray test = new RandomArray(Integer.parseInt(args[0]));
// Print the array
test.printArray();
// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());
// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
System.out.print("Reverse: ");
test.printReverse();
}
}
Let’s look at your sum method first:
public int calSum(int sum) {
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
Why does this method accept a parameter? You just redeclare it on the next line anyway.
Looks good otherwise.
Here’s a cleaned up version:
public int calSum() {
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
Next up, mean average:
public double calMean(int[] array){
//Unsure which elements go here
}
Again, why the parameter?
Recall how we calculate the mean average: sum all elements, then divide by the number of elements.
We’ve already got a method for calculating the sum, so we can use that.
public double calMean() {
int sum = calSum();
int length = numbers.length;
return (double) sum / length;
}
Note the use of (double) here. Without it, cal / length would be integer division, and the result would be rounded to the nearest whole number.
Your method "printArray(int sum)" has the mistake. When you call the method you take a parameter sum, which is not needed. Then you try to create a second local variable with the name sum. This is impossible, because you already have a parameter called sum.
In your for loop you init antoher local variable called sum. You need a different name for that variable, since you only need it for counting the loop.
So remove your parameter sum and rename the variable used in the for loop.
This should work:
import java.util.Arrays;
public class ArrayCalculations
{
private int[] numbers;
public ArrayCalculations(int size)
{
this.numbers = new int[size];
for (int i = 0; i < size; i++)
{
int randomNumber = (int) (Math.random() * 10);
numbers[i] = randomNumber;
}
}
public int calculateSum()
{
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
return sum;
}
public float calculateAverage()
{
float sum = (float) calculateSum();
return sum / numbers.length;
}
public void printArray()
{
System.out.println(Arrays.toString(numbers));
}
public static void main(String[] args)
{
ArrayCalculations ac = new ArrayCalculations(5); // initiates an array with 5 elements
ac.printArray(); // prints the array to console
System.out.println("The sum is: " + ac.calculateSum()); // prints the sum
System.out.println("The average is: " + ac.calculateAverage()); // prints the average
}
}
I'm trying to find the maximum value of the last column and i need to print it out. I tried using the Double.max(); method but it doesn't work for the specific array and I wanted to create an array for the 13th column but it won't let me.
import java.lang.reflect.Array;
public class LabMidterm3 {
public static void main(String[] args) {
double[][] myArray =new double [4][13];
double row = myArray.length;
double column = myArray[0].length;
for (int i=0; i<row;i++){
int sum =0;
for(int j=0; j<column;j++){
double random = (int)(Math.random()*7.0);
myArray[i][j] = random;
sum+=myArray[i][j];
System.out.print(myArray[i][j] + ", ");
double max = Array.getDouble(myArray, 13);
if(j==13){
System.out.print("The max value is: " + max);
}
}
double rowAverage= sum/column;
if(i==1){
System.out.println();
System.out.print("The average is: " +rowAverage);
System.out.println();
}
System.out.println();
}
}
Since you are calculating (and storing) double values, don't cast the random to an int. Next, initialize max to some non-present value guaranteed to be smaller than any value present (like -∞). Then use Math.max(double, double) to update it while you iterate the row. And you can use Arrays.toString(double[]) to print your row. Finally, print the average and max after you populate the array. Something like
double sum = 0;
double max = Double.NEGATIVE_INFINITY;
for (int j = 0; j < column; j++) {
myArray[i][j] = Math.random() * 7.0;
max = Math.max(max, myArray[i][j]);
sum += myArray[i][j];
}
System.out.println(Arrays.toString(myArray[i]));
double rowAverage = sum / column;
if (i == 1) {
System.out.println("The average is: " + rowAverage);
System.out.println("The max is: " + max);
}
import javax.swing.JOptionPane;
public class ArrayOperations
{
public static void main(String[] args)
{
String[] numbers;
numbers = JOptionPane.showInputDialog("Enter your numbers: ");
int numbers1 = Integer.parseInt(numbers);
JOptionPane.ShowMessageDialog(null, "The sum of your numbers is: "
+ getTotal() + "\nThe average of your numbers is: " + getAverage()
+ "\nThe highest number was: " + getHighest + "The lowest number "
+ "was: " + getLowest());
}
public static double getTotal()
{
//Accumulate sum of elements in numbers1 array and return total
double total = 0.0;
for (int index = 0; index < numbers1.length; index++)
total += numbers1[index];
return total;
}
public static double getAverage()
{
//Get average
return getTotal() / numbers1.length;
}
public static double getHighest()
{
//Find highest number entered
double highest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] > highest)
highest = numbers1[index];
}
return highest;
}
public static double getLowest()
{
//Find lowest number entered
double lowest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] < lowest)
lowest = numbers1[index];
}
return lowest;
}
}
So...basically i'm in chapter seven of this starting out with java book and a lot of people's answers are prone to using methods we haven't covered yet... (we are just now learning about arrays) and quite frankly I have no idea how to save user input in an array... I would really appreciate some help. There are actually a plethora of errors with this code, but I figure if I figure out the main one, maybe it'll help me solve the rest of them.
ArrayOperations.java:19: error: incompatible types: String cannot be converted to String[]
numbers = JOptionPane.showInputDialog("Enter your numbers: ");
I changed many thing in your code.
01) Taking a string as input and create a array using the no of white spaces then the string is broken to int array.
02) Passing an array to each and every method so all the elements are calculated.
The code:
import javax.swing.JOptionPane;
public class ArrayOperations
{
public static void main(String[] args)
{
String numbers;
numbers = JOptionPane.showInputDialog("Enter your numbers: ");
int count = 0;
for(int i = 0; i < numbers.length(); i++) {
if(Character.isWhitespace(numbers.charAt(i))) count++;
}
int [] numbers1 = new int [++count];
for(int n = 0; n < count; n++) {
numbers1[n] = Integer.parseInt(numbers.split(" ")[n]);
}
JOptionPane.showMessageDialog(null, "The sum of your numbers is: "
+ getTotal(numbers1) + "\nThe average of your numbers is: " + getAverage(numbers1)
+ "\nThe highest number was: " + getHighest(numbers1) + "\nThe lowest number "
+ "was: " + getLowest(numbers1));
}
public static double getTotal(int[] numbers1)
{
//Accumulate sum of elements in numbers1 array and return total
double total = 0.0;
for (int index = 0; index < numbers1.length; index++)
total += numbers1[index];
return total;
}
public static double getAverage(int[] numbers1)
{
//Get average
return (getTotal(numbers1) / numbers1.length);
}
public static double getHighest(int[] numbers1)
{
//Find highest number entered
double highest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] > highest)
highest = numbers1[index];
}
return highest;
}
public static double getLowest(int[] numbers1)
{
//Find lowest number entered
double lowest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] < lowest)
lowest = numbers1[index];
}
return lowest;
}
}
Hope that this is what you needed.
I am in a beginner Java class and just learning the concept of arrays. We have to use comments to denote the code.
I am trying to make a program that asks the user to enter 20 numbers, stores them in an array and then calculates and displays: the lowest number, the highest number, the total of the numbers and the average of the numbers.
I have a ton of errors when running it through jGrasp and am unsure how to fix them.
Any advice?
public class NumberAnalysisProgram
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
//A constant for the array size
final int SIZE = 20;
//Declare an array to hold the numbers entered by the user
int[] numbers = new int[SIZE];
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
//Declare variable to hold the total
int sum;
//Declare a variable to hold the average
double average;
//Declare a counting variable to use in the loops
int index = 0;
//Explain the program
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers,
and the average.");
//Get the numbers from the user
for (int i = 0; i< numbers.length; i++)
{
System.out.print("Please enter 20 numbers, each seperated by a space: ");
numbers[i] = input.nextInt();
}
//Call a method to calculate the lowest and highest numbers
getLowHigh(numbers);
//Display the lowest and highest numbers
System.out.println("The lowest number is: " + lowest);
System.out.println("The highest number is: " + highest);
//Call a method to calculate the total of the numbers
sum = getTotal(numbers);
//Display the sum/total of the numbers
System.out.println("The total of these numbers are: " + sum);
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
//Display the average of the numbers
System.out.println("The average of these numbers are: " + average);
}
//Method getLowHigh
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
//Method getTotal
public static int getTotal(int[] array)
{
//Loop counter variable
int index;
//Accumulator variable initialized to 0
int total = 0;
//Pull in the numbers from the main method to calculate the total
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
return total;
}
//Method getAverage
public static int getAverage(int[] array)
{
//Loop counter variable
int index;
//Pull in the sum and the numbers from the main method to calculate the average
for(index = 0; index < numbers.length; index++)
{
average = sum / number[index];
}
return average;
}
}
The first problem I can see is that in all of the methods, you never used the arguments. You used a different array, which doesn't exist within those methods.
The second problem is that you're trying to return two values from one method. You can only return one value from a method. So you have to get rid of "return highest;" and make a copy of the method in which there is no "return lowest;", and use each where needed.
The third thing I see (although it isn't causing any errors) is that you could shorten the code by saying
int total = 0;
for(int index = 0; index < numbers.length; index++)
{
total += number[index];
}
instead of
int index;
int total = 0;
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
For starters, the below code is trying to initialize variables to array values that don't exist… These should be removed entirely.
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
There will also be an error with these in the code below because you're not passing them to the function therefore it doesn't exist within this scope.
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
You are also supplying 2 parameters for a function that only calls for one. See below:
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
I think that this is more clean:
public class Main {
public static final int SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
Double total = 0d;
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers, and the average.");
// Get the numbers from the user
System.out.print("Please enter 20 numbers, each seperated by a space: ");
for (int i = 0; i < SIZE; i++) {
Integer currInput = input.nextInt();
numbers.add(currInput);
total += currInput;
}
System.out.println("The lowest number is: " + Collections.min(numbers));
System.out.println("The highest number is: " + Collections.max(numbers));
System.out.println("The total of these numbers are: " + total);
System.out.println("The average of these numbers are: " + (total / SIZE));
}
}
Hope it helps :]