![]() |
Stuck on this code...
Hello I am still very new to java and I've been looking over this code for quite some time. There are two hurdles I am trying to get by with which the later one actually just started happening recently... I am trying to post the largest and smallest index number from the last two methods. The second thing that is happening is that now my code just hangs after I input the rainfall numbers.... any help would be greatly appreciated!!
import java.util.Scanner; import java.text.DecimalFormat; public class Rainfall { public static void main(String[] args) { final int MONTHS = 12; double[] rain = new double[MONTHS]; initRain(rain); double total = totalRain(rain); double average = averageRain(rain, total); double most = mostRain(rain); double least = leastRain(rain); DecimalFormat digit = new DecimalFormat("#.0"); System.out.println("The total rainfall of the year is " + digit.format(total)); System.out.println("The average rainfall of the year is " + digit.format(average)); System.out.println("The month with the highest amount of rain is " + most); System.out.println("The month with the lowest amount of rain is " + least); } public static void initRain(double[] array) { Scanner keyboard = new Scanner(System.in); for (int x = 0; x < array.length; x++) { System.out.print("Enter Rainfall for month " + (x + 1) + ": "); array[x] = keyboard.nextDouble(); } } public static double totalRain(double[] array) { double total = 0; for (int x = 0; x < 12; x++) total += array[x]; return total; } public static double averageRain(double[] array, double total) { return total / array.length; } public static double mostRain(double[] array) {; double maximum = array[1]; int value = 0; for (int i=0; i < 12; i = i++) { if (array[i] >= maximum) maximum = array[i]; value = i; } return value; } public static double leastRain(double[] array) { double minimum = array[0]; int value; for (int i=0; i < 12; i++) { if (array[i] <= minimum) minimum = array[i]; value = i; } return value; } } |
You don't need to put that much work into the least and most methods. Instead, sort the arrays and pull from the first and last:
PHP Code:
PHP Code:
The hang is an infinite loop here: for (int i=0; i < 12; i = i++). Remove the assignment (or just use what I posted since I don't use a loop in that counter).I'd give the averageRain an overload as well: PHP Code:
Also, in the future please choose a better topic title to describe the problem, and use [php][/php] or [code][/code] tags around code to preserve the formatting. |
| All times are GMT +1. The time now is 02:51 PM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.