Temperatures in Java Homework Sample

The data file provided gives the average temperatures for each month of the year, you need to read them and determine the mean, min and max temperatures and the months where the min and max values occur. The temperatures in the data file are in centigrade, after determining the values, convert the values into Fahrenheit and run the analysis again. For more Java programming assignments contact us for a quote.

Solution:

Temp.java

import java.text.DecimalFormat;

public class Temp {
private String [] months= {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};

private static double[] arr;
private static double avg;
private static int maxIndex;
private static int minIndex;
public Temp(double arr1[] ) {
arr=new double[arr1.length];
for(int i=0;i<arr.length;i++) {
arr[i]=arr1[i];
}
avg=0;
maxIndex=0;
minIndex=0;
}

public static double calcAvg() {
double sum=0;
for(int i=0;i<arr.length;i++) {
sum=sum+arr[i];
}
avg=sum/arr.length;
return avg;
}
public static double findMax() {
int m=0;
double max=arr[0];
for(int i=1;i<arr.length;i++) {
if(arr[i]>max) {
max=arr[i];
m=i;
}
}
maxIndex=m;
return max;
}

public static double findMin() {
int m=0;
double min=arr[0];
for(int i=1;i<arr.length;i++) {
if(arr[i]<min) {
min=arr[i];
m=i;
}
}
minIndex=m;
return min;
}

public static void convertToFah() {
for(int i=0;i<arr.length;i++) {
arr[i]=(arr[i]*9/5.0)+32;
}
}

public String toString() {
String pattern = “##.00″;
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String s=””;
s=”Temperature Statistics in Centigrade\n————————————–\nAverage Temperature: “+decimalFormat.format(avg)+”\nHigh Temperature: “+months[maxIndex]+” “+decimalFormat.format(arr[maxIndex])+”\nLow Temperature: “+months[minIndex]+” “+decimalFormat.format(arr[minIndex])+”\n”;
return s;
}
}

TempDriver.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TempDriver {

public static void main(String[] args) throws FileNotFoundException {

double[] temp=new double[12];

String filePath = “C:\\Users\\Raj\\Downloads\\temp(1).dat”;

File file = new File(filePath);
Scanner scnr = new Scanner(file);
String line = scnr.nextLine();
String[] a=line.split(” “);
for(int i=0;i<12;i++) {
temp[i]=Double.parseDouble(a[i]);
}

Temp t=new Temp(temp);
t.calcAvg();
t.findMax();
t.findMin();
System.out.println(t.toString());
t.convertToFah();
t.calcAvg();
t.findMax();
t.findMin();
System.out.println(t.toString());

}

}