Finding the Max Value of the last row of a 2D array - java

I'm trying to find the maximum value of the last column and i need to print it out. I tried using the Double.max(); method but it doesn't work for the specific array and I wanted to create an array for the 13th column but it won't let me.
import java.lang.reflect.Array;
public class LabMidterm3 {
public static void main(String[] args) {
double[][] myArray =new double [4][13];
double row = myArray.length;
double column = myArray[0].length;
for (int i=0; i<row;i++){
int sum =0;
for(int j=0; j<column;j++){
double random = (int)(Math.random()*7.0);
myArray[i][j] = random;
sum+=myArray[i][j];
System.out.print(myArray[i][j] + ", ");
double max = Array.getDouble(myArray, 13);
if(j==13){
System.out.print("The max value is: " + max);
}
}
double rowAverage= sum/column;
if(i==1){
System.out.println();
System.out.print("The average is: " +rowAverage);
System.out.println();
}
System.out.println();
}
}

Since you are calculating (and storing) double values, don't cast the random to an int. Next, initialize max to some non-present value guaranteed to be smaller than any value present (like -∞). Then use Math.max(double, double) to update it while you iterate the row. And you can use Arrays.toString(double[]) to print your row. Finally, print the average and max after you populate the array. Something like
double sum = 0;
double max = Double.NEGATIVE_INFINITY;
for (int j = 0; j < column; j++) {
myArray[i][j] = Math.random() * 7.0;
max = Math.max(max, myArray[i][j]);
sum += myArray[i][j];
}
System.out.println(Arrays.toString(myArray[i]));
double rowAverage = sum / column;
if (i == 1) {
System.out.println("The average is: " + rowAverage);
System.out.println("The max is: " + max);
}

Related

in Java array even average, I am having problem in return

The question is if the number in an array is even then we've to print the sum of even numbers and then return the average. Here I am getting the sum but my average is not returning.
public static double evenAverage(ARRAY arr[]) {
double sum = 0;
int count = 0;
double avg = 0;
for(int i = 0; i<arr.length; i++) {
if(arr[i].num % 2 == 0) {
sum = sum + arr[i].num;
count++;
}
}
for(int i = 0; i<arr.length; i++) {
avg = sum/count;
}
System.out.println("even sum is: " +sum);
System.out.println("average is: ");
return avg;
}
Why are you looping over arr[]
for(int i = 0; i<arr.length; i++) {
avg = sum/count;
}
average can be calculated directly as you have both sum and count.
avg = sum/count;
Moreover, 2nd println statement does not print avg.
rest it should work fine.
I don't see any problem with your code but I have some tips:
The second for loop you have is unnecessary since to calculate the average you only need to do this calculation once
avg = sum/count;
The avg variable is being returned correctly you just need to add it in the print statementas you did with the sum variable so you can see it in the console.

Need this program to run an actual array using a sort method with user input in the scanner class [duplicate]

After several hours, I haven't made progress on making a method to output the average. I also need to make a sort class. Overall, the assignment needs.
Develop methods to:
‘main’ method Print the array
Sort the array
Determine the highest value
Determine the lowest value
Calculate the average value (double)
import java.util.Scanner;
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin=new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number= sin.nextInt();
int array[]=new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers");
for (int i = 0; i < number; i++)
{
array[i]=sin.nextInt();
}
System.out.println ("The highest number in the array is " + max (array) );
System.out.println ("The smallest number in the array is " + min (array) );
//System.out.println ("The average of the numbers in the array is " ;
}
public static int max ( int ... arg )
{
if ( arg.length == 0)
{
System.out.println(" empty arguement list ") ;
return 0;
}
int largest = arg [0];
for (int i = 1; i < arg.length; i++ )
{
if (arg [i] > largest)
largest = arg[i];
}
return largest;
}
public static int min ( int ... arg )
{
if ( arg.length == 0)
{
System.out.println(" empty arguement list ") ;
return 0;
}
int smallest = arg [0];
for (int i = 1; i < arg.length; i++ )
{
if (arg [i] < smallest)
smallest = arg[i];
}
return smallest;
int sum = 0;
for (int d : arg ) sum += d;
double average = 1.0d * sum / arg .length;
this will help you to find average...
To sort find min and max you can use TreeSet collection class. If you are using primitive type or a wrapper class, in this case no need to add any comparison logic. otherwise you need to implement comparator or comparable methods. Here is a example of TreeSet for min and max data http://www.programcreek.com/2009/02/a-simple-treeset-example/ . For calculating average i suggest you can use a local variable and for each time you add a number to TreeSet you can update the average. For eg when you add a new number p to current average value v, calculate latest average as v = (v*size + p)/++size;
In Java 8+ you could use IntStream and IntSummaryStatistics like
int[] arr = { 3, 1, 2 };
IntSummaryStatistics stats = IntStream.of(arr).summaryStatistics();
System.out.printf("Min: %d, Max: %d, Average: %.2f%n", //
stats.getMin(), stats.getMax(), stats.getAverage());
IntStream.of(arr).sorted().forEach(System.out::println);
Calculate the average like this:
int sum = 0;
double avg = 0;
for (int i=0;i<array.length; i++){
sum+=array[i];
}
avg = sum/array.length;

incompatible types - double to int?

Java seems to think that I am attempting to convert or perform some kind of action on one of my double variables. I get the error message
average2.java:23: error: incompatible types: possible lossy
conversion from double to int scores[count++]=score;
I am really confused in that I have not declared anything as an integer thus far, - every variable is a double because I expect to have some decimals. Below is my code :
public static void main (String [] args)
{
double numOf;
double lowest = 100;
double count = 0;
double sum = 0;
double average = 0;
double score;
double scores[] = new double[100]; //[IO.readDouble("Enter Scores, Enter -1 to Quit")];
while ((count <100) &&(( score =IO.readDouble("Enter Scores, (-1 to Quit")) > 0));
{
scores[count++]=score;
}
//This section obtains the highest number that was entered`
double max = scores[0];
for (double i=0; i<scores.length; i++)
if(max < scores[i])max =scores[i];
System.out.println("Maximum is " + max);
// This section obtains the lowest score entered
double min = scores[0];
for (int i=0; i<scores.length; i++)
if (min > scores[i]) min = scores [i];
int sumOf =0;
for (int i=0; i < scores.length; i++)
{
sumOf += scores[i];
}
System.out.println("The sum of all scores is " + sumOf);
System.out.println("Minimum is " + min);
count = count + 1;
average = (sumOf/scores.length);
System.out.println("Average is " + average);
} //end main
} //end class
The error refers to the count variable, which is a double. But ints are valid indices for an array. The error results from using a double as an index where an int was expected for the index.
Declare count to be an int.
You should also declare i to be an int in the first for loop, for the same reason.

Create an array based on a range of values given by the user

What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}

Not ignoring a value?

import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.

Categories