Java min max values - java

Everything is working fine, I just need my output to say the quarter with the highest/lowest rainfall, not the actual values. I am not sure how to tie the quarter and the values together so that the output will be quarter 1, 2, 3 or 4.
import java.util.Scanner;
public class rainfall
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double[] rainfall = new double[4];
double totalRainfall = 0.0;
double max = 0, min = 0;
for (int i=0; i < 4; i++)
{
System.out.print("Enter rainfall for quarter " + (i+1) + ": ");
rainfall[i] = scan.nextDouble();
totalRainfall += rainfall[i];
if (i == 0)
{
max = min = rainfall[i];
}
{
if (rainfall[i] > max)
max = rainfall[i];
else if (rainfall[i] < min)
min = (i + 1);
//min = rainfall[i];
}
}
System.out.println("Total rainfall = "+totalRainfall);
System.out.println("Average rainfall = "+(totalRainfall / 4.0));
System.out.println("Max quarter rainfall = "+ max);
System.out.println("Min quarter rainfall = " + min);
//System.out.println("Max quarter rainfall = "+ maxQuarter);
//System.out.println("Min quarter rainfall = " + minQuarter);
}//end main
}//end class

Just store the indexes instead of the values:
if (rainfall[i] > rainfall[max])
max = i;
else if (rainfall[i] < rainfall[min])
min = i;
System.out.println("Max quarter rainfall = " + max + 1);
System.out.println("Min quarter rainfall = " + min + 1);

You need to track maxQuarter and minQuarter (added as ints) as well as max and min. Like so:
import java.util.Scanner;
public class rainfall
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double[] rainfall = new double[4];
double totalRainfall = 0.0;
double max = 0, min = 0;
// init to Q1 as that's the 1st tested
int maxQuarter = 1, minQuarter = 1;
for (int i=0; i < 4; i++)
{
System.out.print("Enter rainfall for quarter " + (i+1) + ": ");
rainfall[i] = scan.nextDouble();
totalRainfall += rainfall[i];
if (i == 0)
{
max = min = rainfall[i];
}
{
if (rainfall[i] > max) {
max = rainfall[i];
maxQuarter = i + 1;
}
if (rainfall[i] < min) {
min = rainfall[i];
minQuarter = i + 1;
}
}
}
System.out.println("Total rainfall = "+totalRainfall);
System.out.println("Average rainfall = "+(totalRainfall / 4.0));
System.out.println("Max quarter rainfall = "+ max);
System.out.println("Min quarter rainfall = " + min);
System.out.println("Max quarter rainfall = "+ maxQuarter);
System.out.println("Min quarter rainfall = " + minQuarter);
}//end main
}//end class
With these changes, it runs fine for my basic tests:
Enter rainfall for quarter 1: 2
Enter rainfall for quarter 2: 4
Enter rainfall for quarter 3: 6
Enter rainfall for quarter 4: 7
Total rainfall = 19.0
Average rainfall = 4.75
Max quarter rainfall = 7.0
Min quarter rainfall = 2.0
Max quarter rainfall = 4
Minquarter rainfall = 1

You should format your code (Ctrl+Shift+f in Eclipse).
Keep the i index in parallel to the min and max, something like imax, imin. Otherwise you lose the origin of the values like in your case.

Related

when executing program, extra input command causes logical errors java

I am trying to execute a program called AverageRainfall. Most of the input works well (my while statement at the beginning is fine), but there are multiple months under the variable monthRain, and the while statement for monthRain is not functioning with the various months, only the initial input command, which is serving no purpose.
ETA: Posting entire code for testing
import java.util.Scanner; //for Scanner class
public class AverageRainfall
{
public static void main(String[] args)
{
final int NUM_MONTHS = 12; //Months per year
int years; //Number of years
double monthRain; //Rain for a month
double totalRain = 0; //Rainfall accumulator
double average; //Average rainfall
Scanner keyboard = new Scanner(System.in);
{
System.out.print("Enter the number of years: ");
years = keyboard.nextInt();
while (years < 1)
{
System.out.print("Invalid. Enter 1 or greater: ");
years = keyboard.nextInt();
}
}
{
System.out.println("Enter the rainfall, in inches, for each month. ");
monthRain = keyboard.nextDouble();
for(int y = 1; y <= years; y++){
for(int m = 1; m <= NUM_MONTHS; m++){
System.out.print("Year" + y + "month" + m + ": ");
monthRain = keyboard.nextDouble();
}
}
while (monthRain < 0)
{
System.out.print("Invalid. Enter 0 or greater: ");
monthRain = keyboard.nextDouble();
}
}
{
totalRain += monthRain;
average = totalRain / (years * NUM_MONTHS);
System.out.println("\nNumber of months: " + (years * NUM_MONTHS) );
System.out.println("Total rainfall: " + totalRain + " inches");
System.out.println("Average monthly rainfall: " + average + " inches");
}
}
}
This is the entire code.
You were using unnecessary braces. Moreover, some logical flaws were also present in your code. I have fixed your code. Please refer the following code:
import java.util.Scanner; //for Scanner class
public class AverageRainfall {
public static void main(String[] args) {
final int NUM_MONTHS = 12; // Months per year
int years; // Number of years
double monthRain=0; // Rain for a month
double totalRain = 0; // Rainfall accumulator
double average; // Average rainfall
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number of years: ");
years = keyboard.nextInt();
while (years < 1) {
System.out.print("Invalid. Enter 1 or greater: ");
years = keyboard.nextInt();
}
System.out.println("Enter the rainfall, in inches, for each month. ");
for (int y = 1; y <= years; y++) {
for (int m = 1; m <= NUM_MONTHS; m++) {
System.out.print("Year" + y + "month" + m + ": ");
monthRain = keyboard.nextDouble();
while (monthRain < 0) {
System.out.print("Invalid. Enter 0 or greater: ");
monthRain = keyboard.nextDouble();
}
totalRain += monthRain;
}
}
average = totalRain / (years * NUM_MONTHS);
System.out.println("\nNumber of months: " + (years * NUM_MONTHS));
System.out.println("Total rainfall: " + totalRain + " inches");
System.out.println("Average monthly rainfall: " + average
+ " inches");
}
}
What you can do is add to the total of Rain each time the user inputs a month rain. Then you can do the average once he finishes inputting data.
`import java.util.Scanner;
public class test {
public static void main(String[]args){
double monthRain=0;
double totalRain=0;
Scanner keyboard = new Scanner(System.in);
int years = 1;
int NUM_MONTHS = 12;
System.out.println("Enter the rainfall, in inches, for each month. ");
for(int y = 1; y <= years; y++){
for(int m = 1; m <= NUM_MONTHS; m++){
System.out.print("Year" + y + "month" + m + ": ");
monthRain = keyboard.nextDouble();
totalRain+=monthRain;
}
}
int totalMonth = years*NUM_MONTHS;
System.out.println("\nNumber of months: " + totalMonth );
System.out.println("Total Rain: "+totalRain+" inches");
double average = totalRain / totalMonth;
System.out.println("Average monthly rainfall: " + average + " inches");
}
}
`

Calculating Rainfall for four quarters in a user-defined number of years

I'm new to Java, and am attempting to do an assignment...but am feeling lost right about now. We haven't been introduced to arrays yet, so our vocabulary is a bit limited.
1.) Modify your current code so that it will handle multiple years of rainfall data. Give the option to the user to supply the actual number of years they want to enter in the program for evaluation. This program must output the year (i.e. Year 1, Year 2, etc.) for most rainfall and the year with the least amount of total rainfall.
Below is my code:
import java.util.Scanner;
public class Test2OF
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double[] rainfall = new double[4];
double totalRainfall = 0.0;
double max = 0, min = 0;
int year = scan.nextInt();
int maxQuarter = 1;
int minQuarter = 1;
// Prompt user for the number of years
System.out.println("Enter the number of years: ");
year = scan.nextInt();
for (int i=0; i < year*4; i++)
{
System.out.print("Enter rainfall for quarter " + (i+1) + ": ");
rainfall[i] = scan.nextDouble();
totalRainfall += rainfall[i];
if (i == 0)
{
max = min = rainfall[i];
}
{
if (rainfall[i] > max) {
max = rainfall[i];
maxQuarter = i + 1;
}
if (rainfall[i] < min) {
min = rainfall[i];
minQuarter = i + 1;
}
}
}
System.out.println("Total rainfall = "+totalRainfall);
System.out.println("Average rainfall = "+(totalRainfall / 4.0));
System.out.println("Max quarter rainfall = "+ max);
System.out.println("Min quarter rainfall = " + min);
System.out.println("Max quarter rainfall = "+ maxQuarter);
System.out.println("Min quarter rainfall = " + minQuarter);
}//end main
}//end class
Upon compiling, I get this exception when I try to put data in for quarter 5.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Test2OF.main(Test2OF.java:22)
I'm also pretty clueless as to how I can specify what year had the most/least amount of rainfall at the end.
Your help is appreciated! Thank you very much.
problem:
year*4
Your rainfall is only of a size 4 which means it is only good for 1 year which has 4 quarter.
solution:
You need to calculate the number of quarter of the specified number of years and then resize your array by using year*4
sample:
Scanner scan = new Scanner(System.in);
double[] rainfall;
double totalRainfall = 0.0;
double max = 0, min = 0;
int year = 0;
int maxQuarter = 1;
int minQuarter = 1;
System.out.println("Enter the number of years: ");
year = scan.nextInt();
rainfall = new double[year*4]
EDIT:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double[] rainfall;
int curyear = 0;
double totalRainfall = 0.0;
double max = 0, min = 0;
int year = 0;
int maxQuarter = 1;
int minQuarter = 1;
// Prompt user for the number of years
System.out.println("Enter the number of years: ");
year = scan.nextInt();
rainfall = new double[year*4];
for (int i=0; i < year*4 + 1; i++)
{
if((i % 4) == 0 && i != 0)
{
System.out.println();
System.out.println("YEAR: " + ++curyear );
System.out.println("Total rainfall = "+totalRainfall);
System.out.println("Average rainfall = "+(totalRainfall / 4.0));
System.out.println("Max quarter rainfall = "+ max);
System.out.println("Min quarter rainfall = " + min);
System.out.println("Max quarter rainfall = "+ maxQuarter);
System.out.println("Min quarter rainfall = " + minQuarter);
System.out.println();
if(i == (year*4))
break;
}
System.out.print("Enter rainfall for quarter " + (i+1) + ": ");
rainfall[i] = scan.nextDouble();
totalRainfall += rainfall[i];
if (i == 0)
{
max = min = rainfall[i];
}
{
if (rainfall[i] > max) {
max = rainfall[i];
maxQuarter = i + 1;
}
if (rainfall[i] < min) {
min = rainfall[i];
minQuarter = i + 1;
}
}
}
}//end main
new double[4]; this is wrong.
if you get size from user then why you initialized?
give size after user provide size like new double[year];
First thing I notice right off of the bat is
Int year = Scanner.nextInt();
Blahblahblah
year = Scanner.nextInt();
Don't give year a value yet.
Int year;
Year = scanner.nextInt();
As for the rest I don't know if I want to help you on this. It is unethical to assist you because the point of this is to learn. Note that it is perfectly fine to tell you professor that you were unable to complete the assignment and that he would be of better assistance than the internet.
Sent from iPad so please excuse spelling and capitalization mistakes

Calculating the average number in a nesting loop Java

does anyone knows how to calculate the average in a loop. Every time I calculated the average I received 0 or 1. I know that I need use average = (sum) / (salary_annually); but I can't get it to work. Thanks in advance.
import java.util.Scanner;
public class midterm
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
int average=0;
int count = 0;
int salary_annually = 0;
for(int employee =1; employee <= 2; employee++)
{
System.out.println("Employee: " + employee);
for(int year=1; year <= 2; year++)
{
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually ;
if (min >= salary_annually)
{
min = salary_annually;
}
if (max <=salary_annually)
{
max = salary_annually;
}
average = (sum) / (salary_annually);
}
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
I'm guessing the problem here is that you are using integer division. Since the sum and salary_annually are both integers division works slightly different. There is not remainder because dividing two integers gives an int.
For example 1/2 is not .5 as you might expect but instead it is 0. Any fractional number is dropped when doing integer math. As another example 9/5 is not 1.8 but instead 1.
If you want the average then you can either declare sum or salary_annually as a double and declare the average as a double as well.
Change
average = (sum) / (salary_annually);
To
double average=0;// Declare it as `double` rather than `int`
average = (sum) / 2.0;
average is calculated by: average = sum / count;
you need to increment your count variable, otherwise you will always get and ArithmeticException / by zero
The Average is calculated by average = sum / count where average should be of type double.
You did declare the variable count, but didn't use it.
import java.util.Scanner;
public class Calulate {
/**
* #param args
*/
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
double average = 0;
int count = 2;
int salary_annually = 0;
for (int employee = 1; employee <= 2; employee++) {
System.out.println("Employee: " + employee);
for (int year = 1; year <= count; year++) {
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually;
if (min >= salary_annually) {
min = salary_annually;
}
if (max <= salary_annually) {
max = salary_annually;
}
}
average = sum / count;
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}

Calculating the average in a Loop Java

I just found that when I calculate the average for the second user, I get a different result. For example, if I add this number for the first user 10,10,10,20,20. I get 14.0 which is correct. But when I enter the same number for the second user I get 28.0? any ideas?
import java.util.Scanner;
public class midterm
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
double average=0;
int count = 0;
int salary_annually = 0;
for(int employee =1; employee <= 2; employee++)
{
System.out.println("Employee: " + employee);
for(int year=1; year <= 5; year++)
{
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually ;
average = (sum) / 5.0;
if (min >= salary_annually)
{
min = salary_annually;
}
if (max <=salary_annually)
{
max = salary_annually;
}
}
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
sum = 0; // this before 2nd loop
int max = Integer.MIN_VALUE; // these too.
int min = Integer.MAX_VALUE;
for(int year=1; year <= 5; year++)
{
.
.
.
}
average = (sum) / 5.0; // this after 2nd loop
In your solution you are calculating average 5 times inside the loop! and you only get advantage from the fifth time! must be after the loop. average = (sum) / 5.0; after the loop.
You need to zero sum at the end of the loop. As it is, now it just keeps increasing and increasing as the old value is kept in memory, when coming to the next iteration.

Arrays Java - Trying to remove user input requirements

I am creating a program that calculates rainfall for the year etc. I had the first block of code below working with the user input, perfectly. However, I am trying to change the program now, so that the array values are specified (I'm basically trying to eliminate the user input).
Why isn't the second block of code working? I am getting errors at the bottom for r.getTotalRainFall, r.getAverageRainFall etc.
Please note that I had to introduce the array thisYear (this is required).
CODE BLOCK #1:
import java.util.*;
public class Rainfall {
Scanner in = new Scanner(System.in);
int month = 12;
double total = 0;
double average;
double months[];
public Rainfall() {
months = new double[12];
}
public void enterMonthData() {
for (int n = 1; n <= month; n++) {
System.out.print("Enter the rainfall (in inches) for month #" + n + ": ");
months[n - 1] = in.nextDouble();
// Input Validation - Cannot accept a negative number
while (months[n - 1] < 0) {
System.out.print("Rainfall must be at least 0. Please enter a new value.");
months[n - 1] = in.nextDouble();
}
}
}
public double getTotalRainFall() {
total = 0;
for (int i = 0; i < 12; i++) {
total = total + months[i];
}
return total;
}
public double getAverageRainFall() {
average = total / 12;
return average;
}
/**
* Returns the index of the month with the highest rainfall.
*/
public int getHighestMonth() {
int highest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] > months[highest]) {
highest = i;
}
}
return highest;
}
/**
* Returns the index of the month with the lowest rainfall.
*/
public int getLowestMonth() {
int lowest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] < months[lowest]) {
lowest = i;
}
}
return lowest;
}
public static void main(String[]args) {
Rainfall r = new Rainfall();
r.enterMonthData();
System.out.println("The total rainfall for this year is " + r.getTotalRainFall());
System.out.println("The average rainfall for this year is " + r.getAverageRainFall());
int lowest = r.getLowestMonth();
int highest = r.getHighestMonth();
System.out.println("The month with the highest amount of rain is " + (highest+1) + " with " + r.months[highest] + " inches");
System.out.println("The month with the lowest amount of rain is " + (lowest+1) + " with " + r.months[lowest] + " inches");
}
}
CODE BLOCK #2:
package rain;
public class Rain {
int month = 12;
double total = 0;
double average;
double getRainAt[];
public Rain {
getRainAt = new double[12];
}
double getTotalRainFall() {
total = 0;
for (int i = 0; i < 12; i++) {
total = total + getRainAt[i];
}
return total;
}
double getAverageRainFall() {
average = total / 12;
return average;
}
int getHighestMonth() {
int high = 0;
for (int i = 0; i < 12; i++) {
if (getRainAt[i] > getRainAt[high]) {
high = i;
}
}
return high;
}
int getLowestMonth() {
int low = 0;
for (int i = 0; i < 12; i++) {
if (getRainAt[i] < getRainAt[low]) {
low = i;
}
}
return low;
}
public static void main(String[] args) {
// Create an array of rainfall figures.
double[] thisYear = {1.6, 2.1, 1.7, 3.5, 2.6, 3.7,
3.9, 2.6, 2.9, 4.3, 2.4, 3.7 };
int high; // The high month
int low; // The low month
// Create a RainFall object initialized with the figures
// stored in the thisYear array.
Rainfall r = new Rainfall(thisYear);
// Display the statistics.
System.out.println("The total rainfall for this year is " +
r.getTotalRainFall();
System.out.println("The average rainfall for this year is " +
r.getAverageRainFall());
high = r.getHighestMonth();
System.out.println("The month with the highest amount of rain " +
"is " + (high+1) + " with " + r.getRainAt(high) +
" inches.");
low = r.getLowestMonth();
System.out.println("The month with the lowest amount of rain " +
"is " + (low+1) + " with " + r.getRainAt(low) +
" inches.");
}
}
}
I have re-factored the 2 classes
now Rain class only contains the main method whereas all the other logic is contained in the Rainfall class
Rainfall class has a method - getRainAt() to get rain base don the given month
in Rainfall class has a constructor that takes a double array as an argument so it has to be instantiated with this argument provided.
take a look at the classes now and see if this fits your requirement.
import java.util.*;
public class Rainfall {
Scanner in = new Scanner(System.in);
int month = 12;
double total = 0;
double average;
double months[];
public Rainfall(double newmonths[]){
months = newmonths;
}
public void enterMonthData() {
for (int n = 1; n <= month; n++) {
System.out.print("Enter the rainfall (in inches) for month #" + n
+ ": ");
months[n - 1] = in.nextDouble();
// Input Validation - Cannot accept a negative number
while (months[n - 1] < 0) {
System.out
.print("Rainfall must be at least 0. Please enter a new value.");
months[n - 1] = in.nextDouble();
}
}
}
public double getTotalRainFall() {
total = 0;
for (int i = 0; i < 12; i++) {
total = total + months[i];
}
return total;
}
public double getAverageRainFall() {
average = total / 12;
return average;
}
/**
* get rain given the month number
*/
public double getRainAt(int month){
double rainValue = 0;
for (int i = 0; i < months.length; i++) {
if(month == i){
rainValue = months[i];
break;
}
}
return rainValue;
}
/**
* Returns the index of the month with the highest rainfall.
*/
public int getHighestMonth() {
int highest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] > months[highest]) {
highest = i;
}
}
return highest;
}
/**
* Returns the index of the month with the lowest rainfall.
*/
public int getLowestMonth() {
int lowest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] < months[lowest]) {
lowest = i;
}
}
return lowest;
}
}
Rain class only has the main method now
public class Rain {
public static void main(String[] args) {
// Create an array of rainfall figures.
double[] thisYear = { 1.6, 2.1, 1.7, 3.5, 2.6, 3.7, 3.9, 2.6, 2.9, 4.3,
2.4, 3.7 };
int high; // The high month
int low; // The low month
// Create a RainFall object initialized with the figures
// stored in the thisYear array.
Rainfall r = new Rainfall(thisYear);
// Display the statistics.
System.out.println("The total rainfall for this year is "
+ r.getTotalRainFall());
System.out.println("The average rainfall for this year is "
+ r.getAverageRainFall());
high = r.getHighestMonth();
System.out.println("The month with the highest amount of rain " + "is "
+ (high + 1) + " with " + r.getRainAt(high) + " inches.");
low = r.getLowestMonth();
System.out.println("The month with the lowest amount of rain " + "is "
+ (low + 1) + " with " + r.getRainAt(low) + " inches.");
}
}
hope this helps
I'm not sure if this was just a copying error, but in the second block you've called the class Rain, but then you declared r as Rainfall.
Not sure why you are creating a getRainAt class just to initialise it, try using the Rain class constructor to do this.
Replace this:
public class getRainAt {
public getRainAt() {
getRainAt = new double[12];
}
}
With:
public Rain() {
getRainAt = new double[12];
}
and since you are using Rain instead of Rainfall now, in the main method it should be:
Rain r = new Rain();

Categories

Resources