datatypes and arrays in java - arrays

Thoroughly confused on how to do this. What I want to do is to place the city with the lowest min, or max in the output. My understanding is you cannot throw a string in with another datatype in a method. How in the world can I match the name with the lowest temperature?
Lets say I want 3 cities:
I want to make the array 3 then:
Then I will add in the following cities, (Alanta, New York, Richmond)
The cities temperatures are (42.2, 98.8, -12.4)
Min is -12.4
Max is 98.8
That I have, how do I link Richmond's String that is stored in array[2] to temperature's double that is stored in array[2]? Any help is much appreciated.
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.lang.Math;
public class Ex9
{
public static void main(String[] args)
{
String message ="";
double min = 0, max = 0, avg = 0;
int counter = 1;
int numberOfCities = Integer.parseInt(JOptionPane.showInputDialog(null, "How many cities would you like to enter?"));
String[] nameOfCities = new String[numberOfCities];
double[] temperatureOfCities = new double[numberOfCities];
for (int i = 0; i < nameOfCities.length; i++)
{
nameOfCities[i] = JOptionPane.showInputDialog(null, "Please enter the name of city " +counter+" :");
temperatureOfCities[i] = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter the current temperature of the city " + counter +" :"));
message += "City name " + nameOfCities[i] + ".\n"
+ "Temperature of city " + temperatureOfCities[i] + " is degrees\n";
counter++;
}//end numberOfCities loop
if(
JOptionPane.showMessageDialog(null, message + "\nThe average temperature is " +findAvg(temperatureOfCities)+ "\n[Name of city] has the lowest temperature, which is " + findMin(temperatureOfCities) + "\n[Name of city] has the highest temperature, which is " + findMax(temperatureOfCities));
}//end main
public static double findAvg(double[] temperatureOfCities)
{
double sum =0;
for(int i=0;i<temperatureOfCities.length;i++)
{
sum += temperatureOfCities[i];
}
sum = sum/temperatureOfCities.length;
return sum;
}//end findAvg
public static double findMin(double[] temperatureOfCities)
{
double min=0;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] <= temperatureOfCities[0])
{
min = temperatureOfCities[i];
}
}//end for loop
return min;
}//end findMin
public static double findMax(double[] temperatureOfCities)
{
double max=0;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] >= temperatureOfCities[0])
{
max = temperatureOfCities[i];
}
}//end for loop
return max;
}//end findMax
}//end program

Two main approaches here:
1) The procedural approach - just pass both arrays around instead of just one array. If they're kept synchronized there's no problem - just use the same index for both.
2) The object oriented approach - Define a class TemperatureReading with double temperature and string cityName. Then you can make a TemperatureReading[] array and pass it around, and the data is naturally associated.

Change your findMin, findAvg, and findMax methods to return a composite Measurement object.
class Measurement {
final double temperature;
final String cityName;
Measurment(String cityName, double temperature)
{
this.temperature = temperature;
this.cityName = cityName;
}
}
The updated methods could look something like this:
public static Measurement findMax(String[] nameOfCities, double[] temperatureOfCities) {
double maxTemp=0;
String maxName=null;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] >= temperatureOfCities[0])
{
maxTemp = temperatureOfCities[i];
maxName = nameOfCities[i];
}
} //end for loop
return new Measurement(maxTemp, maxName);
}
Now you can use the results like this:
Measurement maxMeasurement = findMax(nameOfCities, temperatureOfCities);
System.out.println(maxMeasurement.cityName + "has a temperature of " + maxMeasurement.temperature);
Similar goes for findMin and findAvg.

Related

How to figure out a set of arrays to add a ranking system for student gpa from a text file

public static void main(String[] args) throws FileNotFoundException
{
File file = new File("studentdata.txt");
try (Scanner scan = new Scanner(file))
{
String[] IDs = new String[1000];
double[] GPAs = new double[1000];
int counter;
counter = 0;
String STUDENTID;
double GPA;
int NUMofSTUD = 0;
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
while (scan.hasNext())
{
STUDENTID = scan.next();
NUMofSTUD ++;
GPA = scan.nextDouble();
IDs[counter] = STUDENTID;
GPAs[counter] = GPA;
List<GpaCount> GpaCounts = new ArrayList<>();
{
int[] index = new int[GPAs.length];
for (int i = 0; i < GPAs.length; i++)
{
int count = 0;
for (int j = 0; j < GPAs.length; j++)
{
if (GPAs[j] > GPAs[i])
{
count++;
}
}
index[i] = count + 1;
Comparator<GpaCount> comparator = (GpaCount o1, GpaCount o2) -> Integer.compare(o1.getCount(), o2.getCount());
Collections.sort(GpaCounts, comparator);
}
}
if (GPA >= 3.5)
{
one ++;
}
if (GPA >= 3.0 && GPA < 3.5)
{
two++;
}
if (GPA >= 2.5 && GPA < 3.0)
{
three++;
}
if (GPA >= 2.0 && GPA < 2.5)
{
four++;
}
if (GPA >= 1.5 && GPA < 2.0)
{
five++;
}
if (GPA >= 1.0 && GPA < 1.5)
{
six++;
}
if (GPA >= .5 && GPA < 1.0)
{
seven++;
}
if (GPA < .5)
{
eight ++;
}
System.out.println("Student ID: " + STUDENTID +
" GPA: " + GPA + " Rank: " + GpaCounts);
}
System.out.println("Histogram of GPA");
System.out.println("GPA 0.0 to 0.4: "+ eight + " students "
+ Stars(eight/10));
System.out.println("GPA 0.5 to 0.9: "+ seven + " students "
+ Stars(seven/10));
System.out.println("GPA 1.0 to 1.5: "+ six + " students "
+ Stars(six/10));
System.out.println("GPA 1.5 to 1.9: "+ five + " students "
+ Stars(five/10));
System.out.println("GPA 2.0 to 2.4: "+ four + " students "
+ Stars(four/10));
System.out.println("GPA 2.5 to 2.9: "+ three + " students "
+ Stars(three/10));
System.out.println("GPA 3.0 to 3.4: "+ two + " students "
+ Stars(two/10));
System.out.println("GPA 3.5 to 4.0: "+ one + " students "
+ Stars(one/10));
System.out.println(NUMofSTUD);
}
}
/* nt[] getRanksArray(double[] array)
{
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] > array[i]) {
count++;
}
}
result[i] = count + 1;
}
return result;
} */
public static String Stars(int number)
{
StringBuilder temp = new StringBuilder();
for(int i=0; i<number; i++){
temp.append("*");
}
return temp.toString();
}
}
I am stuck at the ListGpa, it shows the variable is never read. This a a Java program that takes a text document with student ID and GPA(theoretical). It outputs everything correctly, other than the fact it won't add the rank to the ends of the names.
For both of your questions:
ListGPA is declared but never used and it's simply a warning
suggesting you to remove it it from your code. I looked over your
code and didn't see it being used anywhere after it was declared.
Your rank "*" method is correct, however when you invoke the method
like Stars(one/10) and let's say one is equal to 5, then it's stars(5/10) =
stars(0) because your method parameter is an int and the decimal value is
truncated. I created my own text-file with 10 students at 4.0 GPA each and a
star did print.
My suggestion is to break your program into helper methods to perform each task. For example, I would create a method to read and extract data from your input file and return a list of Students. Then I would create another method that takes the list of Students and perform the next step. The idea is to separate the logic and maintain readability. Your program has issues in it and having all of that logic in one place is extremely messy. I would suggest that you go back and store your input in a list of student objects and work your way from there.
class Student {
/* Ideally you would make these private and create getters/setters */
public int id;
public double gpa;
public Student(int id, double gpa) {
this.id = id;
this.gpa = gpa;
}
/* Overriding toString() and equals() methods is something to think about */
}
public class Demo {
public static void main(String[] args) {
List<Student> students = generateStudentList(new File("studentdata.txt"));
printStudentList(students); // Should output data of all students
}
public static List<Student> generateStudentList(File file) {
List<Student> students = new ArrayList<>();
try (Scanner scanner = new Scanner(file)) {
while(scanner.hasNext()) {
int id = scanner.nextInt();
double gpa = scanner.nextDouble();
students.add(new Student(id, gpa));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return students;
}
public static void printStudentList(List<Student> students) {
System.out.println("Number of students: " + students.size());
for(Student student : students) {
int id = student.id;
double gpa = student.gpa;
System.out.println("Student ID: " + id + "\t" + "GPA: " + gpa);
}
}
}
See how I separated my logic into methods. You can complete this problem by
thinking about what you need to do first. Use your results to solve the next task. It's all a systematic process in order to solve the problem as a whole.
If you have any questions feel free to ask. Best of luck!

Im having trouble passing 2d arrays to my methods, then printing them, and also finding lowest value in certain data fields

So I have all the information fine, but I have 3 problems, printing the methods, passing the array correctly, and in my getMinValue method im trying to get the lowest number out of the array [0][2] , [1][2],[2][2], [3][2],[4][2]. I'm pulling the wrong lowest numbers. Any help would be appreciated! (ignore my comments)
public class MorenoJonathonSnowFallTotal
{
public static void main(String[] args)
{
double [][] array={{3.6,24.6,31.8,26.4,17.5},
{4.7,29.1,33.0,29.2,17.7},{5.5,23.3,41.0,26.7,14.4},
{4.4,18.8,36.1,24.4,11.1},{2.1,10.1,18.8,18.8,8.9}};
/**for(int i=0;i<5;i++){
for(int j=0;j<5;j++) {
System.out.print(array[i][j]+" ");
}
System.out.println("");
} */
//average by city
//average by month
System.out.println(monthAv);
}
public static double getMinValue(double[][] numbers) {
double minValue = numbers[0][2];
for (int j = 1; j < 3; j++) {
for (int i = 2; i < 3; i++) {
if (numbers[j][i] < minValue ) {
minValue = numbers[j][i];
}
}
}
return minValue ;
}
public void monthAv(double [][] arr)
{
double [][] array=arr;
System.out.println("");
System.out.println("The average of November is "+(arr[0][0]+arr[1] .
[0]+arr[2][0]+arr[3][0]+arr[4][0])/5);
System.out.println("The average of December is "+(arr[0][1]+arr[1] .
[1]+arr[2][1]+arr[3][1]+arr[4][1])/5);
System.out.println("The average of January is "+(arr[0][2]+arr[1] .
[2]+arr[2][2]+arr[3][2]+arr[4][2])/5);
System.out.println("The average of Febuary is "+(arr[0][3]+arr[1] .
[3]+arr[2][3]+arr[3][3]+arr[4][3])/5);
System.out.println("The average of March is "+(arr[0][4]+arr[1] .
[4]+arr[2][4]+arr[3][4]+arr[4][4])/5);
}
public void cityAv(double[][] arr)
{
double [][] array=arr;
System.out.println("The average snow fall of Detroit is "+(array[0] .
[0]+array[0][1]+array[0][2]+array[0][3]+array[0][4])/5);
System.out.println("The average snow fall of Chicago is "+(array[1] .
[0]+array[1][1]+array[1][2]+array[1][3]+array[1][4])/5);
System.out.println("The average snow fall of Boston is "+(array[2] .
[0]+array[2][1]+array[2][2]+array[2][3]+array[2][4])/5);
System.out.println("The average snow fall of New York is "+(array[3] .
[0]+array[3][1]+array[3][2]+array[3][3]+array[3][4])/5);
System.out.println("The average snow fall of Washington D.C is "+ .
(array[4][0]+array[4][1]+array[4][2]+array[4][3]+array[4][4])/5);
}
}
There are too much syntax errors here and I'm not going to even mention them. I suggest you look for some java tutorials or books on the internet since there are a lot of them. Moreover the code is not complete. Also, the question is not very clear.
Assuming that each row of your array are the values for a city and each column of those rows are the values of the city in the given month:
Read the comments to get a general understanding of this problem while following this code:
package morenojonathonsnowfalltotal;
public class MorenoJonathonSnowFallTotal {
// Register cities
public static final String[] CITIES = {
"Detroid",
"Chicago",
"Boston",
"New York",
"Washington D.C."
};
// Register months
public static final String[] MONTHS = {
"November",
"December",
"January",
"February",
"March"
};
// ROW = City!
// COL = Month!
public static final double[][] DATA_2DARRAY = {
//1º row will be temperatures of Detroid on November, December...
//2º row will be temperatures of Chicago on November, December... AND SO ON AND SO FORTH
{3.6, 24.6, 31.8, 26.4, 17.5},
{4.7, 29.1, 33.0, 29.2, 17.7},
{5.5, 23.3, 41.0, 26.7, 14.4},
{4.4, 18.8, 36.1, 24.4, 11.1},
{2.1, 10.1, 18.8, 18.8, 8.9}
};
public static void main(String[] args) {
int column = 2;
System.out.println("The lowest value for column "+column+" is: "+GetMinimumColumnValue(column));
// You might mean or want...
System.out.println("The lowest total snowfall on "+MONTHS[column]+" is: "+GetMinimumColumnValue(column));
// Separate outputs.
System.out.println("");System.out.println("");System.out.println("");
ComputeMonthsAverageSnowfall();
// Separate outputs
System.out.println("");System.out.println("");System.out.println("");
ComputeCitiesAverageSnowfall();
}
public static double GetMinimumColumnValue(int column) {
/*
Init to the maximum double value so we ensure
that the value will be updated on the first iteration
*/
double lowest = Double.MAX_VALUE;
double current;
// Traverse each month looking for the minimum value.
for (int i = 0; i < MONTHS.length; i++) {
current = DATA_2DARRAY[i][column];
/* Update the minimal value if the current
element is lesser than the lowest we've found so far*/
if(current<lowest) lowest=current;
}
return lowest;
}
public static void ComputeMonthsAverageSnowfall() {
double average;
for (int i = 0; i < MONTHS.length; i++) {
// Compute it's average snowfall
average = ComputeAverage(GetColumn(i));
// Note that this time we have to get it's COLUMN values. hence GetColumn method.
System.out.println("The average snowfall on "+MONTHS[i]+" was "+average);
}
}
/**
* Given an index of a column, copies all its values and returns it as an array.
* #param idx_col
* #return
*/
public static double[] GetColumn(int idx_col){
// A Month register will hold as many registers as cities there are.
// HENCE
// The column will hold as many rows as the original data
double[] col = new double[CITIES.length];
// For each city, copy its values.
for (int i = 0; i < col.length; i++) {
col[i] = DATA_2DARRAY[i][idx_col];
}
return col;
}
public static void ComputeCitiesAverageSnowfall() {
double average;
// For each city...
for (int i = 0; i < CITIES.length; i++) {
// Compute it's average snowfall
average = ComputeAverage(DATA_2DARRAY[i]);
System.out.println("The average snowfall on "+CITIES[i]+" was "+average);
}
}
/**
* Computes the average value of this double array
* #param array
* #return
*/
public static double ComputeAverage(double[] array){
double average = 0;
// Sum each value from the array we want to compute average.
for (int i = 0; i < array.length; i++) {
average = average + array[i];
}
// Return that sum divided by the total amount of elements that were in the array
return (average/((double) array.length));
}
}

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0 error in my Java program

I made this sample program for a while, and I'm figuring out how to add the sum of the two employees' pay I inputted in the array. Any suggestions?
import javax.swing.JOptionPane;
public class Sample {
public static void main (String[] args)
{
String Name;
int i, HoursWorked, Rate, Pay=0, TotalPay=0, GrandTotalPay=0;
int CivStatus=0, Single=500, Married=1000;
System.out.println("Name\t\t\t\tCivil Status Code\t\t\tPay");
int [] Employees = new int [2];
for (i=0; i<Employees.length; i++)
{
Name=JOptionPane.showInputDialog("Enter your name: ");
HoursWorked=Integer.parseInt(JOptionPane.showInputDialog("Enter hours worked: "));
Rate=Integer.parseInt(JOptionPane.showInputDialog("Enter hourly rate: "));
Pay=HoursWorked*Rate;
CivStatus=Integer.parseInt(JOptionPane.showInputDialog("Enter your civil status: \nEnter [1] if single.\nEnter [2] if married."));
if(CivStatus==1){
{
TotalPay=Pay-Single;
}
}
if(CivStatus==2){
{
TotalPay=Pay-Married;
}
}
GrandTotalPay=Employees[0]+Employees[1];
System.out.println(Name+"\t\t\t\t"+CivStatus+"\t\t\t\t\t"+Pay);
}
System.out.println("The sum of the pay is: "+GrandTotalPay);
}
}
Array index Out of bounds exception occurs when you try to access a memory location not present in the array.
You are doing same in
for (i=0; i<=Employees.length; i++)
Instead, do
for (i=0; i<Employees.length; i++)
After you calculate each Pay, add it to TotalPay.
Like:
TotalPay = TotalPay + Pay;
Or,
TotalPay += Pay;
The next thing, you actually are not using the array here. If you want to keep the Pays in the array, you need an array of size 2.
int[] Employees = new int[2];
Another thing, when traversing an array, do it like this:
for(i = 0; i < Employees.Length; i++) {}
Array indexing starts from 0, and goes up to (size - 1), so you cannot use <= Employees.Length here.
Array index starts from 0. If you want to loop through all elements use indices from 0 till length.
Change i<=Employees.Length into i<Employees.Length
Check the code below and make changes. Note: changed Pay into an Array for holding pay of each employees
import javax.swing.JOptionPane;
public class Sample {
public static void main (String[] args)
{
String Name;
int i, HoursWorked, Rate, TotalPay=0, GrandTotalPay=0;
int CivStatus=0, Single=500, Married=1000;
System.out.println("Name\t\t\t\tCivil Status Code\t\t\tPay");
int [] Pay = new int [2];
int [] Employees = new int [2];
for (i=0; i<Employees.length; i++)
{
Name=JOptionPane.showInputDialog("Enter your name: ");
HoursWorked=Integer.parseInt(JOptionPane.showInputDialog("Enter hours worked: "));
Rate=Integer.parseInt(JOptionPane.showInputDialog("Enter hourly rate: "));
Pay[i]=HoursWorked*Rate;
CivStatus=Integer.parseInt(JOptionPane.showInputDialog("Enter your civil status: \nEnter [1] if single.\nEnter [2] if married."));
if(CivStatus==1){
{
TotalPay=Pay[i]-Single;
}
}
if(CivStatus==2){
{
TotalPay=Pay[i]-Married;
}
}
GrandTotalPay+=Pay[i];
System.out.println(Name+"\t\t\t\t"+CivStatus+"\t\t\t\t\t"+Pay[i]);
}
System.out.println("The sum of the pay is: "+GrandTotalPay);
}
}
Thanks.

How do I calculate median from an array from a different class?

I have an array of values in a different class. I am trying to calculate max, min and median from this array. I have my methods created but all values still display "0" when I run the program. Can someone please point out what I am doing wrong?
import java.util.*;
public class SortedListStats
{
public int maxTemp;
public int minTemp;
public int medianTemp;
public SortedListStats()
{
this.maxTemp = maxTemp;
this.minTemp = minTemp;
this.medianTemp = medianTemp;
InputOutput io = new InputOutput(); //This is my other class that has the array.
}
public int maxTemp(int[] io) //method to determine maximum temperature
{
int max = io[0];
for(int i = 0; i < io.length; i++)
{
if(max < io[i])
max = io[i];
}//end for statement
return max;
}//end method maxTemp
public int minTemp(int[] io) //method to determine mininum temperature
{
int min = io[0];
for(int i = 0; i < io.length; i++)
{
if(min > io[i])
min = io[i];
}//end for statement
return min;
}//end class minTemp
public int medianTemp(int[] io)
{
Arrays.sort(io);
int sum = 0;
int count = 0;
int median;
for(int i = 0; i > io.length; i++)
{
sum = sum + io[i];
count++;
}
median = sum/count;
return median;
}//end method medianTemp
}//end class SortedListStats
What code are you using to call the methods on this class? The first three lines of the constructor don't do anything. If you're expecting them to call your calculation methods, then they need to be after "new InputOutput()" and they need to be function calls. Like:
this.maxTemp = maxTemp(io.getValues());
You should refrain from naming your functions the same as your member variables to avoid confusion. For instance, the "maxTemp()" function could be "calculateMaxTemp()" instead.

Random Array Sorting

Is it possible to sort (ascending) the randomly generated integer array for the following code? If, so how?
import java.util.Random;
public class RandomArraySorter {
public static void main(String args[]){
Random random = new Random();
int array[] = new int[10];
//number of integer spaces within the array:
for(int i = 0; i < 10; i++){
//random numbers from 1 to 100:
array[i] = random.nextInt(100) + 1;
System.out.print(array[i] + " ");
}
} //end of main
} //end of class
You can sort with:
Arrays.sort(array);

Resources