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

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.

Related

How do I get 4 digits number but without any digit number repeated?

As title said, I want to randomly generate a 4-digit number (it's okay to have zero in the first digit), but the number itself couldn't contain the same number.
For example, 1234 is okay, 2234 is not okay, because 2 has repeated.
Moreover, if it got repeated, then create another number again until the 4-digit number has no longer the same number within.
I couldn't figure it out. I stuck on some point, especially in while-loop.
Here's my code with C#.
Please help me with this.
public class GuessNumber
{
public int[] answer;
public void newGame()
{
int[] answer = new int[4];
var random = new Random(Guid.NewGuid().GetHashCode());
for (int i = 0; i < answer.Length; i++)
{
answer[i] = random.Next(0, 10);
}
this.answer = RandomCheck(answer);
}
public int[] RandomCheck(int[] answer)
{
bool repetition = true;
for (int i = 0; i < answer.Length; i++)
{
do
{
repetition = false;
for (int k = 0; k < i; k++)
{
if (answer[i] != answer[k]) continue;
else
{
newGame();
continue;
}
} while (repetition);
return answer;
}
Please help with this, make it could automatically generate the right number.

Fast way to compare frequent input data and storing MAX and MIN values

Let's say I have input data every millisecond.
After 5 seconds I want to output the MAX and MIN Value of the last 5 second time window.
What will be here the fastest way to compare frequent integer input data? I put a very simple example. Is it bad to use something like this in general? Is there a faster way but without using array for buffering?
myMainFuntion() {
int static currentMIN = 30000; // Just initialize to a value that will never be output by getSensorData
int static currentMAX = 0;
int static acquisition_counter = 0;
a = getSensorData() // called each 1 ms
if (a > currentMAX) {
currentMAX = a;
}
if (a < currentMIN) {
currentMIN = a;
}
acquisition_counter++;
if (acquisition_counter == 5000) {
output(MAX);
output(MIN);
}
}
It seems OK, there is not much to be optimized in your function, except for a few details:
the return type should be void instead of omitted.
a is not defined.
you should output currentMIN and currentMAX instead of MIN and MAX.
you should reset the values of the min and max variables after the output.
it is more idiomatic to ut the static keyword in front of the type.
Here is the modified code:
void myMainFuntion(void) {
static int currentMIN = 30000; // Just initialize to a value that will never be output by getSensorData
static int currentMAX = 0;
static int acquisition_counter = 0;
int a;
a = getSensorData() // called every 1 ms
if (a > currentMAX) {
currentMAX = a;
}
if (a < currentMIN) {
currentMIN = a;
}
acquisition_counter++;
if (acquisition_counter == 5000) {
output(currentMAX);
output(currentMIN);
currentMAX = 0;
currentMIN = 30000;
acquisition_counter = 0;
}
}

Returning Arrays from Methods

So I have to display the marks that are below average, and all the marks that are above average.
I don't know where to go with this next but here's what I have so far:
public static void main (String[]args) {
int[]marks={50,60,30,90,70,40,80,44};
int average=average(marks);
int[]resultBelowAverage=getBelowAverage(marks,average);
printIntArray(resultBelowAverage);
int[]resultAverageandAbove=getAverageandAbove(marks,average);
printIntArray(resultAverageandAbove);
}
This next method is used to calculate the average. I got the right answer for this one which is 58.
public static int average(int[] marks) {
int i=0;
int total=0;
for(i=0;i<marks.length;i++){
total=total+marks[i];
}
int average=total/i;
return average;
}
This next method gets how many values in the array are below average.
public static int countBelowAverage (int[] numbers,int av){
int size=0;
for(int i=0;i<numbers.length;i++) {
if (numbers[i]<av) {
size=size+1;
}
}
return size;
}
This next method gets how many values in the array are above average.
public static int countAboveAverage (int[] numbers,int av) {
int size=0;
for(int i=0;i>=numbers.length;i++) {
if (numbers[i]>=av) {
size=size+1;
}
}
return size;
}
This next method gets which values in the array are below average. I think this is where I went wrong.
public static int[] getBelowAverage(int[]numbers,int av) {
int size=countBelowAverage(numbers,av);
int[]belowAverage=new int[size];
return belowAverage;
}
This next method gets which values in the array are above average.
public static int[] getAverageandAbove(int[] numbers,int av) {
int size=countAboveAverage(numbers,av);
int[]AboveAverage=new int[size];
return AboveAverage;
}
This last method prints the arrays that are classified into below average and above average.
public static void printIntArray(int[]x) {
for(int i=0;i<x.length;i++){
System.out.println (x[i]);
}
}
In your method getAverageandAbove you make an array, but you do not put anything in it.
you should loop through your numbers array again, and fill your AboveAverage array with the values that are greater than the average.
Try something like this to get the below average array
public static int[] getBelowAverage(int[]numbers,int av){
int size=countBelowAverage(numbers,av);
int[]belowAverage=new int[size];
int j = 0;
for (int i = 0; i < numbers.length; i++){
if (numbers[i] < av){
belowAverage[j] = numbers[i];
j++;
}
}
return belowAverage;
}
Do similar for the above average method
In your methods you just creating arrays of proper size, an empty arrays and returning them. You should put some marks that are below / above average to these arrays before returning
Like here:
int[]belowAverage=new int[size];
//you have an empty array just after creation with nothing inside
//enter here marks from the marks array that are below average
return belowAverage;
Exactly the same situation here:
int[]AboveAverage=new int[size];
//you have an empty array just after creation with nothing inside
//enter here marks from the marks array that are above average
return AboveAverage;
You may use an algorithm from peeskillet's solution to do it.

datatypes and arrays in java

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.

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