I am making a program for a java class of mine that asks this:
Write A Rainfall class that stores the total rainfall for each of 12 months into an array of doubles. The program should have methods that return the following:
The total rainfall for the year
The average monthly rainfall
The month with most rain
The month with least rain
Demonstrate the class in a complete program. (Do not accept negative numbers for monthly rainfall figures)
import java.util.Scanner;
import java.io.*;
public class apples{
public static void main (String[] args){
Scanner kenny = new Scanner(System.in);
double rain[]=new double[13];
double sum = 0;
double avg =0;
double most =0;
double least =0;
System.out.println("Your local weather man here getting paid to tell you the wrong weather!!");
System.out.println("");
System.out.println("Please enter in the following rainfall for the months ahead: ");
System.out.println("Month\tRainfall (In inches)");
System.out.print("January: ");
rain [0] = kenny.nextDouble();
System.out.print("February: ");
rain [1] = kenny.nextDouble();
System.out.print("March: ");
rain [2] = kenny.nextDouble();
System.out.print("April: ");
rain [4] = kenny.nextDouble();
System.out.print("May: ");
rain [5] = kenny.nextDouble();
System.out.print("June: ");
rain [6] = kenny.nextDouble();
System.out.print("July: ");
rain [7] = kenny.nextDouble();
System.out.print("August: ");
rain [8] = kenny.nextDouble();
System.out.print("September: ");
rain [9] = kenny.nextDouble();
System.out.print("October: ");
rain [10] = kenny.nextDouble();
System.out.print("November: ");
rain [11] = kenny.nextDouble();
System.out.print("December: ");
rain [12] = kenny.nextDouble();
//(Or rain[] = 1,2,3,4,5,6,7,8,9,10,11,12);
sum = rain[0] + rain[1] + rain[2] + rain[3] + rain[4] + rain[5] + rain[6] + rain[6] + rain[7] + rain[8] + rain[9] + rain[10] + rain[11] + rain[12] ;
avg = (rain[0] + rain[1] + rain[2] + rain[3] + rain[4] + rain[5] + rain[6] + rain[6] + rain[7] + rain[8] + rain[9] + rain[10] + rain[11] + rain[12]) / 12;
System.out.println("The sum of all the rain is: " + sum);
System.out.println("The average rainfall was:" + avg + " inches");
System.out.print("The month with the most rain was: ");
}
private static void getMaxValue(double[] rain) {
getMaxValue(rain);
System.out.println(getMaxValue(rain));
System.out.println("The month with the least rain was: ");
}
private static void getMinValue(double[] rain) {
getMinValue(rain);
System.out.println(getMaxValue(rain));
}}
I've got most of it ready to go. I just am wondering how to get the "Max" and "Min" from the numbers that are entered.
Any help would be great!!
you can find max or min by looping array .and change return type void to double so method will return max rain ;
private static double getMaxValue(double[] rain) {
double max=0;
for(double i : rain){
if(i>max){
max=i;
}
}
return max;
}
and use this as;
System.out.println(getMaxValue(rain));
and same for min;
private static double getMinValue(double[] rain) {
double min=Double.MAX_VALUE;
for(double i : rain){
if(i<min){
min=i;
}
}
return min;
}
but in your code there is lot of mistakes
1)
double rain[]=new double[13];
this should be
double rain[]=new double[12];
because this is array length .so you have 12 months .
2) you have missed
rain [3]
3) you assign to 13 index by it should be 12 .
rain [13] = kenny.nextDouble(); --> rain [12] = kenny.nextDouble();
so this is the complete example .
public class apples {
public static void main(String[] args) {
Scanner kenny = new Scanner(System.in);
double rain[] = new double[12];
double sum = 0;
double avg = 0;
double most = 0;
double least = 0;
System.out.println("Your local weather man here getting paid to tell you the wrong weather!!");
System.out.println("");
System.out.println("Please enter in the following rainfall for the months ahead: ");
System.out.println("Month\tRainfall (In inches)");
System.out.print("January: ");
rain[0] = kenny.nextDouble();
System.out.print("February: ");
rain[1] = kenny.nextDouble();
System.out.print("March: ");
rain[2] = kenny.nextDouble();
System.out.print("April: ");
rain[3] = kenny.nextDouble();
System.out.print("May: ");
rain[4] = kenny.nextDouble();
System.out.print("June: ");
rain[5] = kenny.nextDouble();
System.out.print("July: ");
rain[6] = kenny.nextDouble();
System.out.print("August: ");
rain[7] = kenny.nextDouble();
System.out.print("September: ");
rain[8] = kenny.nextDouble();
System.out.print("October: ");
rain[9] = kenny.nextDouble();
System.out.print("November: ");
rain[10] = kenny.nextDouble();
System.out.print("December: ");
rain[11] = kenny.nextDouble();
//(Or rain[] = 1,2,3,4,5,6,7,8,9,10,11,12);
sum = rain[0] + rain[1] + rain[2] + rain[3] + rain[4] + rain[5] + rain[6] + rain[7] + rain[8] + rain[9] + rain[10] + rain[11];
avg = sum / 12;
System.out.println("The sum of all the rain is: " + sum);
System.out.println("The average rainfall was:" + avg + " inches");
most =getMaxValue(rain);
least=getMinValue(rain);
System.out.println("The max rain is: " + most);
System.out.println("The min rain is: " + least);
}
private static double getMaxValue(double[] rain) {
double max = 0;
for (double i : rain) {
if (i > max) {
max = i;
}
}
return max;
}
private static double getMinValue(double[] rain) {
double min = Double.MAX_VALUE;
for (double i : rain) {
System.out.println(i);
if (i < min) {
min = i;
}
}
System.out.println(min);
return min;
}
}
but you can use a array witch contain all the months.the advantage of this is you loop dynamically rather than hard cording .and you can warn when input negative easily .the good approach is follow .
public class apples {
public static void main(String[] args) {
Scanner kenny = new Scanner(System.in);
double rain[] = new double[12];
double sum = 0;
double avg = 0;
double most = 0;
double least = 0;
System.out.println("Your local weather man here getting paid to tell you the wrong weather!!");
System.out.println("");
System.out.println("Please enter in the following rainfall for the months ahead: ");
System.out.println("Month\tRainfall (In inches)");
String months[]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
for (int i=0;i<months.length;i++) {
System.out.println(months[i]+" :");
double val = kenny.nextDouble();
while(val<0){
System.out.println("negatives not allowed ! enter again");
val = kenny.nextDouble();
}
rain[i]=val;
sum+=val;
}
avg = sum / 12;
System.out.println("The sum of all the rain is: " + sum);
System.out.println("The average rainfall was:" + avg + " inches");
most =getMaxValue(rain);
least=getMinValue(rain);
System.out.println("The max rain is: " + most);
System.out.println("The min rain is: " + least);
}
private static double getMaxValue(double[] rain) {
double max = 0;
for (double i : rain) {
if (i > max) {
max = i;
}
}
return max;
}
private static double getMinValue(double[] rain) {
double min = Double.MAX_VALUE;
for (double i : rain) {
System.out.println(i);
if (i < min) {
min = i;
}
}
System.out.println(min);
return min;
}
}
Java 8 has a much easier mechanism for manipulating data such as this without any need for looping or temporary variables.
If you have Java 8 you can use the following:
double rain[] = {3, 2, 7, 9, 10};
double totalRainfall = Arrays.stream(rain).sum;
double maxRainfall = Arrays.stream(rain).max().getAsDouble();
double minRainfall = Arrays.stream(rain).min().getAsDouble();
double avgRainfall = Arrays.stream(rain).average().getAsDouble();
That's much easier to read and understand than the traditional method.
Related
Java
How do I get the months to match up with the correct inputed number?
Hello, when I print the statements for the month with the lowest and highest precipitation, the months do not match the numbers. The numbers for the least and highest amounts are correct but the month doesn't correspond. Thank you!
import java.util.Scanner;
public class rain{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Double a[] = new Double[12];
int year = 0;
String city = "";
String[] eachMonth = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
double lowest = 50.0;
int lowestIndex = -1;
double highest = 0.0;
int highestIndex = -1;
double sum = 0;
double average = 0;
double totalPrecipitation = sum;
int feet = 0;
int inches = 0;
System.out.println("Enter city name");
city = scanner.next();
do {
System.out.println("Enter four digit number between 1900 and 2025 ");// prompt user for height in feet
year = scanner.nextInt();
if (year < 1900 || year > 2025) {
System.out.println("Error invalid input enter number between 190 and 2025"); //must be positive whole number of tickets
}
} while (year < 1900 || year > 2025);
System.out.println("Enter the precipitation for the following months ");
double inputVal;
for (int monthCount = 0; monthCount < eachMonth.length; monthCount++) {
while (true) {
System.out.print(eachMonth[monthCount].concat(" : "));
inputVal = scanner.nextDouble();
if (inputVal > 50.0 || inputVal < 0.0)
System.out.println("Please enter value in the range [0.0-50.0]");
else {
a[monthCount] = inputVal;
break;
}
}
}
for (int monthIndex = 0; monthIndex < eachMonth.length; monthIndex++)
{
if (a[monthIndex] > highest)
highest = a[monthIndex];
highestIndex = monthIndex;
if (a[monthIndex] < lowest)
lowest = a[monthIndex];
lowestIndex = monthIndex;
sum = sum + a[monthIndex];
}
totalPrecipitation = sum;
average = sum / 12;
feet = (int)totalPrecipitation/12;
inches = (int)(totalPrecipitation%12);
System.out.println("Precipitation Statistics for " + city + " in " + year + " is:");
for (int monthCount = 0; monthCount < eachMonth.length; monthCount++) {
System.out.println(eachMonth[monthCount] + ":" + a[monthCount]);
}
System.out.println("The total precipitation for the year was: " + feet + " feet " + inches + " inches ");
System.out.println("The average monthly precipitation for the year was: " + average + "inches");
System.out.println("The month with the least amount of precipitation in inches was in " + eachMonth[lowestIndex] + " with " + lowest + " inches");
System.out.println("The month with the most amount of precipitation in inches was in " + eachMonth[highestIndex] + " with " + highest + " inches");
}
}
Java uses {} to wrap blocks of code.
if (a[monthIndex] > highest)
highest = a[monthIndex];
highestIndex = monthIndex;
if (a[monthIndex] < lowest)
lowest = a[monthIndex];
lowestIndex = monthIndex;
This code is executed in the following way:
if (a[monthIndex] > highest) {
highest = a[monthIndex];
}
highestIndex = monthIndex;
if (a[monthIndex] < lowest) {
lowest = a[monthIndex];
}
lowestIndex = monthIndex;
So to fix the problem you have to specify execution blocks:
if (a[monthIndex] > highest) {
highest = a[monthIndex];
highestIndex = monthIndex;
}
if (a[monthIndex] < lowest) {
lowest = a[monthIndex];
lowestIndex = monthIndex;
}
Here is a suggestion. Instead of prompting twice for input in case of an error, put the first prompt outside the while loop. And a slight re-arrangement might make it somewhat simpler (but there is nothing wrong with the way you did it).
System.out.println(
"Enter four digit number between 1900 and 2025 ");
while (true) {
year = scanner.nextInt();
if (year >= 1900 && year <= 2025) {
break;
}
System.out.println(
"Error invalid input enter number between 1900 and 2025");
}
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);
}
}
I want to calculate the average numbers using arrays. I want the program asks for the amount of grades and after I want to put the grade numbers.
After I want to get the average output in a double.
This is my code so far:
public class Average {
public static void main(String[] args)
{
//int n = MyConsole.readInt("Enter number of grades: " );
int a = MyConsole.readInt("Enter grade 1: " );
int b = MyConsole.readInt("Enter grade 2: " );
int c = MyConsole.readInt("Enter grade 3: " );
int[] numbers = new int[]{a,b,c};
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}
Don't know what your class MyConsole is doing, but I guess is a Scanner:
Your code improved will be something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of grades: " );
int n = sc.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.print("Enter grade "+ (i + 1) + ": ");
int a = sc.nextInt();
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
}
OUTPUT (2 grades):
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 5
Average value of array elements is : 3.0
OUTPUT (5 grades):
Enter number of grades: 5
Enter grade 1: 10
Enter grade 2: 20
Enter grade 3: 30
Enter grade 4: 10
Enter grade 5: 50
Average value of array elements is : 24.0
NOTE
double average = sum / n;
performs an int division, so you won't have any decimal places! I would propose a fast cast:
double average = sum / (double) n;
With new output:
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 4
Average value of array elements is : 2.5
GUESS using your own class:
public static void main(String[] args) {
int sum = 0;
int n = MyConsole.readInt("Enter number of grades: " );
for (int i = 0; i < n; i++) {
int a = MyConsole.readInt("Enter grade "+ (i + 1) + ": ");
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
thank you !
Sorry for the poor explanation.
This is my first question
this it the code after edit:
import java.util.Scanner;
public class Average {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of grades: ");
int n = sc.nextInt();
int sum = 0;
int[] numbers = new int[n];
for(int i=0; i < numbers.length ; i++)
{
System.out.println("Enter grade " + (i + 1) + " :");
int a = sc.nextInt();
sum = sum + a;
}
double average = sum / (double) n;
System.out.println("Average value of array elements is : " + average);
sc.close();
}
}
Program to Calculate Average Using Arrays:
public class Inter1 { //name of the class
public static void main(String[] args) {//main method
int number[]={40,56,23,56,87,23,78}; //declaring the int array
int sum=0;
for (int s:number){ //for each
sum +=s;
}
int ave=sum/number.length; //to get the average
System.out.println("the average is "+ave); //out put
}
}
package inter1;
import static java.time.Clock.system;
import java.util.Scanner;
public class Inter1 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int total=0;
System.out.println("Enter how many number that do u wanna enter ?? ");
int num= in.nextInt();
int numbers[]=new int[num];
for (int i=0;i<numbers.length;i++){
System.out.println(i+1+":"+"enter the your numbers ? ");
numbers[i]=in.nextInt();
}
for (int i=0;i<numbers.length;i++){
total+=numbers[i];
}
int average =total/numbers.length;
System.out.println("the average is "+average);
}
}
public class Inter1 { //name of the class
public static void main(String[] args) { //main method
System.out.println("==============================");
int num[]={34,56,78,78,34,2,33,99,100,56}; //int array
int total=0;
for (int i=0;i<num.length;i++){ //for loop
total+=num[i];
}
int avrage1=total/num.length; //output
System.out.println("The average is "+avrage1);
}
}
So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions.
import java.util.Scanner;
public class MinMax {
public static void main (String [] args) {
#SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;
System.out.println("Enter five numbers.");
System.out.println();
while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}
for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}
}
Default your min to a number out of range (like Double.MAX_VALUE), and max to Double.MIN_VALUE. You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double). Something like,
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.
Sorry if I'm being bothersome. But I am stuck on another part of my HW problem. I am now tasked at instead of having an salesperson 0, salespersons start with 1. I have tried to solve this by parsing the strings i to an integer and adding 1. Seemed like it would work. However, for some reason the calculating of min is not correct. It stays at 0. I've tried stepping through the code and seeing why, but I cannot see it.
import java.util.Scanner;
public class Cray {
public static void main(String[] args){
final int SALESPEOPLE = 5;
int[] sales = new int[SALESPEOPLE];
int sum, randomValue, numGreater = 0;
int max = sales[0];
int min = sales[0];
int maxperson = 0;
int minperson = 0;
Scanner scan = new Scanner(System.in);
for (int i=0; i<sales.length; i++)
{
//To attempt print out the information of salesperson 0 and salesperson 1, I returned the integer value of i and added one.
System.out.print("Enter sales for salesperson " + Integer.valueOf(i+1) + ": ");
sales[i] = scan.nextInt();
//max if statemnent works fine and is correct
if(sales[i] > max){
max= sales[i];
maxperson = i;
}
//For some reason max is calculating but not min.
if(sales[i] < min){
min = sales [i];
minperson= i;
}
}
System.out.println("\nSalesperson Sales");
System.out.println("--------------------");
sum = 0;
for (int i=0; i<sales.length; i++)
{
System.out.println(" " + Integer.valueOf(i+1) + " " + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
System.out.println("Average sales: " + sum/5);
System.out.println();
System.out.println("Salesperson " + Integer.valueOf(maxperson+1) + " had the most sales with " + max );
System.out.println("Salesperson " + Integer.valueOf(minperson+1) + " had the least sales with " + min);
System.out.println();
System.out.println("Enter any value to compare to the sales team: ");
randomValue = scan.nextInt();
System.out.println();
for(int r=0; r < sales.length; r++){
if(sales[r] > randomValue){
numGreater++;
System.out.println("Salesperson " + Integer.valueOf(r+1) + " exceeded that amount with " + sales[r]);
}
}
System.out.println();
System.out.println("In total, " + numGreater + " people exceeded that value");
}
}
The problem is that the min is never set as all positive sales will be > 0
You should initialise min as a large value so that a positive sales figure can be less then the minimum value specified in your if statement:
if (sales[i] < min) {
You could use:
int min = Integer.MAX_VALUE;