I want to start off by saying I am not very experienced and I am sorry if this has been answered. I have been trying to find an answer for a while and have not been able to.
I am working on a project where the user inputs numbers into an array. These numbers represent temperatures for different days. The days are obviously the position in the array. I need to find a way to print the temperatures from least to greatest without sorting the array.
So if the user entered [56, 45, 67, 41, 59, 70] that means that it was 56 degrees at position 0 (day 1), 67 degrees at position 2 (day 3). I need to keep the position of the array the same so the days remain with the temps when it prints out.
Edit: I have attached the code I have on my project so far. The HighestOrdered method is the method I dont know what to do or where to start. For the HighestOrdered method as I said above I need to have it print out the temps with the day (the position in the array) and I am not sure how to do that.
This is the code I have so far:
public class Weather {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] high = new int[30];
int [] low = new int[30];
Init (high);
Init(low);
LoadData(high,low);
Report(high, low);
FindAvg(high,low);
Lowest(high, low);
Highest(high,low);
}
public static void Init(int A[])
{
for(int i = 0; i < A.length; i++)
{
A[i] = 510;
}
}
public static void Report(int[] H, int[] L)
{
System.out.println("Day High Low");
for(int i = 0; i < H.length; i++)
{
System.out.println(i + " " + H[i] + " " + L[i]);
}
}
public static void LoadData(int[] H, int[] L)
{
int day = 0;
while(day < 30)
{
try {
int high = Integer.parseInt(JOptionPane.showInputDialog("please enter the high"));
H[day] = high;
} catch (NumberFormatException e) {
}
try {
int low = Integer.parseInt(JOptionPane.showInputDialog(" Please enter the low"));
L[day] = low;
} catch (NumberFormatException e) {
}
day++;
}
}
public static void FindAvg(int[] H, int[] L){
int sumHigh = 0;
int avgHigh;
int sumLow = 0;
int avgLow;
for(int i : H)
sumHigh += i;
avgHigh = sumHigh/H.length;
for(int i : L)
sumLow += i;
avgLow = sumLow/L.length;
System.out.println("The average for the high is: " + avgHigh);
System.out.println("The average for the low is: " + avgLow);
}
public static void Highest(int[] H, int[] L)
{
int highestHigh = -1000;
int dayHigh = 0;
int highestLow = -1000;
int dayLow = 0;
for(int i = 0; i < H.length; i++)
{
if(H[i] > highestHigh && H[i] != 510)
{
highestHigh = H[i];
dayHigh = i;
}
}
System.out.println("\n" + "The highest high is: " + highestHigh + " degrees." + "\n" +
"This temperature was recorded on day: " + dayHigh);
for(int i = 0; i < L.length; i++)
{
if(L[i] > highestLow && L[i] != 510)
{
highestLow = L[i];
dayLow = i;
}
}
System.out.println("\n" + "The highest low is: " + highestLow + " degrees." + "\n" +
"This temperature was recorded on day: " + dayLow);
}
public static void Lowest(int[] H, int[] L)
{
int lowestHigh = 1000;
int dayHigh = 0;
int lowestLow = 1000;
int dayLow = 0;
for(int i = 0; i < H.length; i++)
{
if(H[i] < lowestHigh)
{
lowestHigh = H[i];
dayHigh = i;
}
}
System.out.println("\n" + "The lowest high is: " + lowestHigh + " degrees." + "\n" +
"This temperature was recorded on day: " + dayHigh);
for(int i = 0; i < L.length; i++)
{
if(L[i] < lowestLow)
{
lowestLow = L[i];
dayLow = i;
}
}
System.out.println("\n" + "The lowest low is: " + lowestLow + " degrees." + "\n" +
"This temperature was recorded on day: " + dayLow);
}
public void HighestOrdered(int[] H)
{
}
}
Here's a start.
From your array, create a sorted Map, say
Map<Integer,Integer> mymap = new TreeMap<Integer,Integer>.
You will use temp for the key and the day for the value. e.g., from your example data,
myMap.put(56,1);
myMap.put(45,2);
(Note - in the real code you'd iterate over the array to put the values.)
Then you can iterate over the keys and values (or the entries) in myMap.
Here is a small example to show how this can be done. Only the auxiliary index array is sorted, the original temp array is not changed.
public static void main(String[] args) {
final int [] temp = {56, 45, 67, 41, 59, 70};
Integer [] index = new Integer[temp.length];
for (int i = 0; i < index.length; i++) {
index[i] = i;
}
Arrays.sort(index, new Comparator<Integer>() {
#Override
public int compare(Integer a, Integer b) {
return temp[a] - temp[b];
}
});
for (Integer i : index) {
System.out.printf("temp %d on day %d%n", temp[i], i);
}
}
This gives the output:
temp 41 on day 3
temp 45 on day 1
temp 56 on day 0
temp 59 on day 4
temp 67 on day 2
temp 70 on day 5
Instead of your current array, you can create an object array with each object having two elements: the day and the corresponding temperature.
Sort this array by the temperature value and then print it.
Related
I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15
I am working on creating an algorithm to maximize profit from a .txt file where each line is the price of a certain stock on a day (Starting with day 0).
The output of my program should be "[day you should buy the stock, day you should sell the stock, profit made]".
For example:
Text file:
12, 45, 3, 15, 60, 23, 4
The output should be [2, 4, 57].
My code returns the actual VALUES and not the index of those values.
My output: [3, 60, 57].
I am a beginner, and I cannot seem to find out what to do to produce the correct output! Help would be very much appreciated!
(Trade is a separate class that returns (in, out, profit)).
[EDIT]: I am supposed to do this recursively, and make sure the the overall time cost of the solution is O(n log n)!
Here is my code:
(Apologies if it is messy/things are in it that aren't needed! :) )
import java.util.*;
import java.lang.Math;
import java.io.*;
public class Test_BestTrading
{
public static void main(String[] args) throws Exception
{
//open file
String fileName = args[0];
File inFile = new File(fileName);
Scanner fin = new Scanner(inFile);
int count = 0;
//find out length of array
while(fin.hasNext())
{
fin.nextLine();
count++;
}
fin.close();
int[]p = new int[count];
fin = new Scanner(inFile);
//read numbers into array
for(int i =0; i < count; i++)
p[i] = Integer.parseInt(fin.nextLine());
Trade trade = BestTrade(p, 0, p.length-1);
System.out.println("[" + trade.in + ", " + trade.out + ", " + trade.profit + "]");
}
public static Trade BestTrade(int[] p, int in, int out)
{
if (p.length <= 1)
return new Trade(in, out, out-in);
//Create two arrays - one is left half of "p", one is right half of "p".
int[] left = Arrays.copyOfRange(p, 0, p.length/2);
int[] right = Arrays.copyOfRange(p, p.length/2, p.length);
// Find best values for buying and selling only in left array or only in right array
Trade best_left = BestTrade(left, 0, left.length-1);
Trade best_right = BestTrade(right, 0, right.length-1);
// Compute the best profit for buying in the left and selling in the right.
Trade best_both = new Trade(min(left), max(right), max(right) - min(left));
if (best_left.profit > best_right.profit && best_left.profit > best_both.profit)
return best_left;
else if (best_right.profit > best_left.profit && best_right.profit > best_both.profit)
return best_right;
else
return best_both;
}
public static int max(int[] A)
{
int max = 0;
for(int i=0; i < A.length; i++)
{
if(A[i] > max)
max = A[i];
}
return max;
}
public static int min(int[] A)
{
int min = 100000;
for(int i=0; i < A.length; i++)
{
if(A[i] < min)
min = A[i];
}
return min;
}
}
Once you have your array of numbers, you could simply run a for loop to detect the lowest value and the greatest value as well as the indices of each number.
int greatestDifference = 0;
int indexLowest = 0;
int indexHighest = 0;
for(int i = 0; i < values.length; i++)
for(int j = i + 1; j < values.length; j++)
if(values[i] - values[j] < greatestDifference){
greatestDifference = values[i] - values[j];
indexLowest = i;
indexHighest = j;
}
System.out.println("Buy value is " + values[indexLowest] + " on day " + (indexLowest + 1) + ".");
System.out.println("Sell value is " + values[indexHighest] + " on day " + (indexHighest + 1) + ".");
System.out.println("Net gain is " + Math.abs(greatestDifference));
Check it -
public class BuySellProfit {
public static void main(String[] args) {
int[] a = { 12, 45, 3, 15, 60, 23, 4 };
int min = a[0];
int max = a[0];
int minIndex=0;
int maxIndex=0;
for (int count = 0; count < a.length; count++) {
if (a[count] > max) {
max = a[count];
maxIndex=count;
}
}
System.out.println("Max = " + max);
for (int count = 0; count < a.length; count++) {
if (a[count] < min) {
min = a[count];
minIndex=count;
}
}
System.out.println("min=" + min);
profit(a, minIndex, maxIndex);
}
private static void profit(int a[], int i, int j) {
int profit = a[j] - a[i];
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);
list.add(j);
list.add(profit);
System.out.println(list);
}
}
Output :-
Max = 60
min=3
[2, 4, 57]
You just return the index number instead of Value,
It will work.. BTW your code is OK.
import java.util.Scanner;
public class Example4 {
public static void main(String[] args) {
//System.out.println("input the valuer:");
Scanner x =new Scanner(System.in);
for( int i=1;i<13;i++){
System.out.println("Profit for month" +i);
System.out.println("input the valuer :");
float valuer1 =x.nextFloat();
float result=0;
result+=valuer1;
System.out.println("Total profits for months:"+result);
}
}
}
I have written a BubbleSort program and it works great, gives me a good output and does its job sufficiently. But I am unable to make the program re-execute after sorting through once. I.e. the program completes a sort of 10000 unique numbers and outputs the time it takes and the amount of steps it took, but doesn't execute again, say for another 999 times after that?
In short, can anyone help me get my program to run through itself 1000 times so I am able to get an average of execution time?
Here is the code:
public class BubbleSort {
public static void main(String[] args) {
int BubArray[] = new int[] { #10000 unique values unsorted# };
System.out.println("Array Before Bubble Sort");
for (int a = 0; a < BubArray.length; a++) {
System.out.print(BubArray[a] + " ");
}
double timeTaken = bubbleSortTimeTaken(BubArray);
int itrs = bubbleSort(BubArray);
System.out.println("");
System.out.println("Array After Bubble Sort");
System.out.println("Moves Taken for Sort : " + itrs + " moves.");
System.out.println("Time Taken for Sort : " + timeTaken
+ " milliseconds.");
for (int a = 0; a < BubArray.length; a++) {
System.out.print(BubArray[a] + " ");
}
}
private static int bubbleSort(int[] BubArray) {
int z = BubArray.length;
int temp = 0;
int itrs = 0;
for (int a = 0; a < z; a++) {
for (int x = 1; x < (z - a); x++) {
if (BubArray[x - 1] > BubArray[x]) {
temp = BubArray[x - 1];
BubArray[x - 1] = BubArray[x];
BubArray[x] = temp;
}
itrs++;
}
}
return itrs;
}
public static double bubbleSortTimeTaken(int[] BubArray) {
long startTime = System.nanoTime();
bubbleSort(BubArray);
long timeTaken = System.nanoTime() - startTime;
return timeTaken;
}
}
and here are the results output (note it is limited to just one run):
Unsorted List :
[13981, 6793, 2662, 733, 2850, 9581, 7744 .... ]
Sorted List with BubbleSort
Moves Taken to Sort : 1447551 Moves.
Time Taken to Sort : 1.2483121E7 Milliseconds.
[10, 11, 17, 24, 35, 53, 57, 60, 78, 89, 92 ... ]
Edited code...
public class BubbleSort {
static double bestTime = 10000000, worstTime = 0; //global variables
public static void main(String[] args) {
int BubArray[] = new int[]{3,5,3,2,5,7,2,5,8};
System.out.println("Array Before Bubble Sort");
for(int a = 0; a < BubArray.length; a++){
System.out.print(BubArray[a] + " ");
}
System.out.println("\n Entering Loop...");
for(int i=0; i<1000;i++)
{
bubbleSortTimeTaken(BubArray, i);
}
int itrs = bubbleSort(BubArray);
System.out.println("");
System.out.println("Array After Bubble Sort");
System.out.println("Moves Taken for Sort : " + itrs + " moves.");
System.out.println("BestTime: " + bestTime + " WorstTime: " + worstTime);
System.out.print("Sorted Array: \n");
for(int a = 0; a < BubArray.length; a++){
System.out.print(BubArray[a] + " ");
}
}
private static int bubbleSort(int[] BubArray) {
int z = BubArray.length;
int temp = 0;
int itrs = 0;
for(int a = 0; a < z; a++){
for(int x=1; x < (z-a); x++){
if(BubArray[x-1] > BubArray[x]){
temp = BubArray[x-1];
BubArray[x-1] = BubArray[x];
BubArray[x] = temp;
}
itrs++;
}
}
return itrs;
}
public static void bubbleSortTimeTaken(int[] BubArray, int n)
{
long startTime = System.nanoTime();
bubbleSort(BubArray);
double timeTaken = (System.nanoTime() - startTime)/1000000d;
if(timeTaken > 0)
{
if(timeTaken > worstTime)
{
worstTime = timeTaken;
}
else if(timeTaken < bestTime)
{
bestTime = timeTaken;
}
}
System.out.println("Loop number: "+n + " Time Taken: " + timeTaken);
}
}
Move the method below
private static int bubbleSort(int[] BubArray)
in to some other class extending Thread. May be you can create new threads each time execution finishes. A static instance variable in root class can be used to hold the times.
Question: what is wrong with my arrays, and how do I fix it?
Details:
I initialized the array in the main method, and the values were set in one method. I called the array values in a 2nd method, and everything was fine.
When I tried to call the array in a 3rd method, I got the out of bounds error, even though the size of the array is exactly the same.
I was trying to call the array in order to copy it, and then sort the 2nd array.
thank you
private static WeatherLocation[] WeatherSpots = new WeatherLocation[6];
private static Scanner Input = new Scanner(System.in);
public static void main(String[] args)
{int Count;
for(Count = 0 ; Count < 6; Count++)
WeatherSpots[Count] = new WeatherLocation();
WeatherSpots[0].LocationID = "Tciitcgaitc";
WeatherSpots[1].LocationID = "Redwood Haven";
WeatherSpots[2].LocationID = "Barrier Mountains";
WeatherSpots[3].LocationID = "Nina's Folly";
WeatherSpots[4].LocationID = "Scooly's Hill";
WeatherSpots[5].LocationID = "Twin Cones Park";
SetUp();
String Command = "";
while(!Command.equals("Quit")) {
Menu();
System.out.print("Enter Command: ");
Command = Input.nextLine();
if(Command.equals("Post"))
PostTemperatureInfo();
if(Command.equals("Daily"))
WeeklyReport();
else if (Command.equals("HighLow"))
Sorting();
}
}
public static void PostTemperatureInfo()
{
Scanner LocalInput = new Scanner(System.in);
int K;
int Temp;
//...then get the values for each location...
System.out.println( "Enter the Temperature for each weather station below:\n");
System.out.println( "---------------------------------------------------------------");
for(K = 0 ; K < 6 ; K++) {
System.out.println( "Weather Station: " + WeatherSpots[K].LocationID); //Display the location of the fishing spot...
System.out.print( "Enter Temperature:\t"); //Get the count...
Temp = LocalInput.nextInt();
System.out.println( "---------------------------------------------------------------");
WeatherSpots[K].CatchCount = Temp;
}
System.out.println("");
System.out.println("");
System.out.println("");
}
public static void WeeklyReport()
{
for(K = 0 ; K < 6 ; K++)
{System.out.println( "" + WeatherSpots[K].LocationID +"\t\t" + WeatherSpots[K].CatchCount + "\t\t" + String.format("%.2f", (WeatherSpots[K].CatchCount - 32) * 5 / 9));
}
}
public static void Sorting()
{int K = 0;
for(K = 0 ; K < 6 ; K++);
{int [] copycat = new int[K];
System.arraycopy(WeatherSpots[K].CatchCount, 0, copycat[K], 0, 6);
System.out.println("" + copycat[K]);
Arrays.sort(copycat, 0, K);
System.out.println("Minimum = " + copycat[0]);
System.out.println("Maximum = " + copycat[K -1]);
}
}
}
The problem is that you are allocating an array copycat that is only K integers long, and then you are trying to fit 6 elements into it, even when K == 0. I don't understand your code enough to figure out what the right indexes are, but that's the source of your problem.
Actually, I don't believe that your code as posted will compile. This line from Sorting():
System.arraycopy(WeatherSpots[K].CatchCount, 0, copycat[K], 0, 6);
seems mighty suspicious. The first and third arguments to System.arraycopy are supposed to be arrays, but copycat[K] is an int. Apparently so is WeatherSpots[K].CatchCount.
EDIT:
It seems from your comments and code that the Sorting() routine is just supposed to print the min and max values of WeatherSpots[K].CatchCount. This can be done much more easily than you are doing. Here's one way:
public static void Sorting() {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (WeatherLocation loc : WeatherSpots) {
final int count = loc.CatchCount;
if (count < min) {
min = count;
}
if (count > max) {
max = count;
}
}
System.out.println("Minimum = " + min);
System.out.println("Maximum = " + max);
}
Q: Why not use "array.length" instead of a hard-coded "6"?
Q: I'd really discourage you from using that indentation style, if you can avoid it.
Anyway - this should work (I have not tried it myself):
public static void Sorting() {
for(int K = 0 ; K < WeatherSpots.length ; K++) {
int [] copycat = new int[K];
System.arraycopy(
WeatherSpots[K].CatchCount, 0, copycat[K], 0, WeatherSpots.length);
System.out.println("" + copycat[K]);
Arrays.sort(copycat, 0, K);
System.out.println("Minimum = " + copycat[0]);
System.out.println("Maximum = " + copycat[K -1]);
}
}
The main thing was to get rid of the extraneous ";" after the "for()" loop.
This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
I am writing a java program that gets the rainfall for each month. It's working perfectly, but I just need to know how to get the index of a month - for example, there is an output statement: The month with the lowest amount of rain is 1 with 1.6 inches. How do I get the '1', which is the index of the lowest month? I can get the actual lowest rainfall figure fine, but not the index.
I have tried months[n-1], however I am still getting an error "non-static variable months cannot be referenced from a static context".
Any help would be great. Thanks.
// EDIT
Here is the code. I tried to play around with the static, but that just gave me more errors? So the months[n] part at the bottom is where I'm stuck.
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 setMonths()
{
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;
}
public double getHighestMonth()
{
double highest=0;
for ( int i = 0; i < 12; i++)
{
if ( months[i] > highest)
{
highest = months[i] ;
}
}
return highest;
}
public double getLowestMonth()
{
double lowest = Double.MAX_VALUE;
for ( int n = 0; n < month; n++)
{
if (months[n] < lowest )
{
lowest = months[n];
}
}
return lowest;
}
public static void main(String[]args)
{
Rainfall r =new Rainfall();
r.setMonths();
System.out.println("The total rainfall for this year is " + r.getTotalRainFall());
System.out.println("The average rainfall for this year is " + r.getAverageRainFall());
System.out.println("The month with the highest amount of rain is " + months[n] + "with" + r.getHighestMonth() "inches");
System.out.println("The month with the lowest amount of rain is " + months[n] "with" + r.getLowestMonth() "inches");
}
}
/// EDIT #2 - Ok, so the above code works when getting user input for each month. Now I'm trying to set the values in the array thisYear (i.e. remove user input). The calculations no longer work. What have I done wrong?
package Rainfall;
public class Rainfall {
int month = 12;
double total = 0;
double average;
double getRainAt[];
public Rainfall() {
getRainAt = new double[12];
}
double getTotalRain() {
for (int i = 0; i < 12; i++) {
total = total + getRainAt[i];
}
return total;
}
double getAverageRain() {
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.getTotalRain());
System.out.println("The average rainfall for this year is " +
r.getAverageRain());
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.");
}
}
non-static variable months cannot be referenced from a static context
This compile time time error comes when you access non static member from static member or block
like-
class Test{
private int i=0;
public static void main(String[] args){
i=1; //This will populate that error.
}
}
I think we can look this problem from little different way
class RainFall{
private double minFall;
private double maxFall;
public void setMinFall(double minFall) {
this.minFall = minFall;
}
public double getMinFall() {
return minFall;
}
public void setMaxFall(double maxFall) {
this.maxFall = maxFall;
}
public double getMaxFall() {
return maxFall;
}
}
public class RainFallMeasure{
public static void main(String[] args) {
Map<Integer,RainFall> rainFalls=new HashMap<Integer,RainFall>();
RainFall janRainFall = new RainFall();
janRainFall.setMinFall(1);
janRainFall.setMaxFall(1.6);
rainFalls.put(Calendar.JANUARY, janRainFall);
RainFall febRainFall = new RainFall();
...
rainFalls.put(Calendar.FEBRUARY, febRainFall);
}
}
You can find index with this method
public class TEST {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double temp[] = {1, 5, 3};
System.out.print(getIndex(temp,3));
}
//takes 2 parameters one is array and other is the value for which you want find index
public static int getIndex(double[] temp, int value)
{
int i ;
for( i= 0; i< temp.length; i++)
{
if(temp[i] == value)
{
return i;
}
}
return -1;
}
}
In place of temp you can use your months while passing parameters.
An alternate approach is to redesign your application so that the methods compute the indexes of the months with the highest and lowest rainfall, instead of computing the rainfaill amounts themselves. The idea is that you can always lookup the actual values on demand, once you have the index.
I've patched the code for you so that it does just this, and took the liberty to correct a couple of "static" errors.
You can play with this working application and tune it as you wish:
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");
}
}
ADDENDUM
To answer your follow-up question, you need to provide a constructor for your Rainfall object that takes in the rainfall data and store this data in a field of the object. This is what you want:
public class Rainfall {
private double[] amounts;
public Rainfall(double[] amounts) {
this.amounts = amounts;
}
double getTotalRain() {
double total = 0.0;
for (int i = 0; i < amounts.length; i++) {
total += amounts[i];
}
return total;
}
double getAverageRain() {
return getTotalRain() / amounts.length;
}
int getHighestMonth() {
int high = 0;
for (int i = 0; i < amounts.length; i++) {
if (amounts[i] > amounts[high]) {
high = i;
}
}
return high;
}
int getLowestMonth() {
int low = 0;
for (int i = 0; i < 12; i++) {
if (amounts[i] < amounts[low]) {
low = i;
}
}
return low;
}
/**
* Returns the total rain the given month number. Month numbers
* start at 0, not 1.
*/
double getRainForMonth(int monthNumber) {
return amounts[monthNumber];
}
public static void main(String[] args) {
// Sample data for testing
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, starting at 0
int low; // The low month, stating at 0
// Create a RainFall object initialized with amounts from above array.
Rainfall r = new Rainfall(thisYear);
// Display the statistics.
System.out.println("The total rainfall for this year is " + r.getTotalRain());
System.out.println("The average rainfall for this year is " + r.getAverageRain());
high = r.getHighestMonth();
System.out.println("The month with the highest amount of rain is " + (high + 1)
+ " with " + r.getRainForMonth(high) + " inches.");
low = r.getLowestMonth();
System.out.println("The month with the lowest amount of rain is " + (low + 1)
+ " with " + r.getRainForMonth(low) + " inches.");
}
}