Finding the lowest value in the array - java

int min = temperature[0];
//Here, i have initialized the minium array.
else if(temperature[i] < min) {
min = temperature[i];
And here i have compared the values in the array. But as the initialization of min is 0. It is going to minimum value zero all the time. How do i fix it. Here is my whole code.
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
int min = temperature[0];
int max = temperature[0];
int counter = 0;
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
counter += temperature[i];
if (temperature[i] > max) {
max = temperature[i];
}
else if(temperature[i] < min) {
min = temperature[i];
}
}
int average = counter / temperature.length;
System.out.println("Displaying the average temperature:" + average);
System.out.println("The lowest temperature is:" + min);
System.out.println("The highest temperaature is:" + max);
}
}

Remove the else, logically - if the value is less than the current minimum we want to update current minimum (regardless of the state of the current maximum). We can actually make it clearer using Math.max(int, int) and Math.min(int, int). And, we can't default min and max to initial values without having read the input (unless we use unambiguously absurd values). Like,
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, counter = 0;
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
counter += temperature[i];
max = Math.max(max, temperature[i]);
min = Math.min(min, temperature[i]);
}
int average = (int) (counter / (double) temperature.length);
System.out.println("Displaying the average temperature:" + average);
System.out.println("The lowest temperature is:" + min);
System.out.println("The highest temperaature is:" + max);
Otherwise, you need two loops. Finally, note you were using integer math in calculating average. You presumably want floating point math.
Or, even better, use IntSummaryStatistics like
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
}
IntSummaryStatistics iss = IntStream.of(temperature).summaryStatistics();
System.out.println("Displaying the average temperature:" + iss.getAverage());
System.out.println("The lowest temperature is:" + iss.getMin());
System.out.println("The highest temperaature is:" + iss.getMax());
System.out.println("The total of all values is:" + iss.getSum());

The solution is to initialize min to the first value of your array, if the array had at least one value. You could also set it to Integer.MAX_VALUE if you really want.

Related

min max in array issue

So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions.
import java.util.Scanner;
public class MinMax {
public static void main (String [] args) {
#SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;
System.out.println("Enter five numbers.");
System.out.println();
while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}
for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}
}
Default your min to a number out of range (like Double.MAX_VALUE), and max to Double.MIN_VALUE. You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double). Something like,
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.

Why does my code output ridiculous numbers with the provided set? I'm trying String.format

I am using these numbers: 5,4,3.5,10,20,40,80,93.33,-1. It will work with something simple with only 5 numbers like: 5,4,3,2,1. What is going on? I am trying to use String.format to shorten the number if that is the issue. Do you guys notice anything within my code that I could do differently to maybe avoid this. This is the output with the provided set:
The minimum is -1.0, the maximum is 2.147483647E9, and the average is 2.38609322E8
-238609317.00
-238609318.00
1908874325.00
-238609312.00
-238609302.00
-238609282.00
-238609242.00
-238609229.00
-238609323.00
Desired Output
The Minimum is 3.5, The maximum is 93.33, and the average is 31.978749999999998
Score 5.0 is -26.978749999999998 from the average
Score 4.0 is -27.978749999999998 from the average
Score 3.5 is -28.478749999999998 from the average
Score 10.0 is -21.978749999999998 from the average
Score 20.0 is -11.978749999999998 from the average
Score 40.0 is 8.021250000000002 from the average
Score 80.0 is 48.02125 from the average
Score 93.33 is 61.35125 from the average
public static void main(String[] args)
{
int count = 0;
int arrayLength;
double min = 99999;
double max = 0;
double average;
double sum = 0;
JOptionPane.showMessageDialog(null, "This program will display the average as well as each numbers distance from the average");
// need to put loop here.
arrayLength = IO.readInt("How many numbers will you be entering?");
if (arrayLength <= 0 || arrayLength > 100)
{
JOptionPane.showMessageDialog(null, "Nothing entered, program will close.");
System.exit(0);
}
double[] array = new double[arrayLength];
for (int i = 0; i <arrayLength; i++)
{
array[i] = IO.readInt("Enter number: " + (i+1));
count++;
}
for (int i = 0; i <arrayLength; i++)
{
sum = (array[i] + sum);
if (array[i] <= min)
{
min = array[i];
}
if (array[i] > max)
{
max = array[i];
}
}
average = (sum / arrayLength);
System.out.println("The minimum is " + min + ", the maximum is " + max + ", and the average is " + average);
double[] array2 = new double[arrayLength];
for (int i = 0; i <arrayLength; i++)
{
array2[i] = (array[i] - average);
}
for (int i = 0; i <arrayLength; i++)
{
System.out.println(String.format("%.2f", array2[i]));
}
}
I don't know what happens when you do IO.readInt and put it into a double, but it isn't liable to be what you want...

why is my count increasing when entering 0, it should exit the loop

I been working on this all night but couldn't make anything out it. I want my code to sum all the numbers the user enter, count how many times the user enters the number. then calculate the average.
and then find the max and min, easy right. well yeah if i was to be allowed to use arrays but this is for review and I hate while loops.
here's my code.
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
// double char1=0;
double min = integer;
double max = integer;
// char letter = 'q';
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
Here's the output:
Please enter an integer:
3
The sum of your numbers is: 3.0
The number of values entered is: 1
Please enter an integer:
2
The sum of your numbers is: 5.0
The number of values entered is: 2
Please enter an integer:
1
The sum of your numbers is: 6.0
The number of values entered is: 3
Please enter an integer:
0
The sum of your numbers is: 6.0
The number of values entered is: 4
The average of your sum is: 1.5
The max integer is: 3.0
The min integer is: 0.0
when the count increases by 1 my average comes out wrong. but why is 0 been counted as part of count and why my min always output 0 and not what the user enters. any and all help is much appreciated.
p.s. i have tried numerous ways but it doesnt work. if i try to change my count to start at -1 it solves my problem at hand with average but the count increases anyways so i know its incorrect. also the min problem stays there.
thanks guys
You need to add if condition to avoid increment when you enter 0.
You can use this code
// setting starting min and max value.
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
sum += integer;
if (integer != 0) { // added if condition
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
if (integer < min) // changed 'else if' to 'if'
min = integer;
}
}
System.out.println("Max : " + max);
System.out.println("Min : " + min);
Try this:
For these cases it is best to use the conditional do while. And initialize min at the maximum value allowed.
double integer;
double sum = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = Double.MAX_VALUE;
double max = 0;
do {
System.out.print("Please enter an integer: ");
integer = input.nextInt();
if (integer >0) {
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
if (integer < min)
min = integer;
}
} while (integer != 0);
System.out.println("avg: "+sum/count);
System.out.println("max: "+max);
System.out.println("min: "+min);
you will need to add an extra if condition to make it work.
I have made few changes as below in your code and it is working as expected.
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = integer;
double max = integer;
while (true) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
if(integer != 0)
{
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
else
break;
}
double integer = 1;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
while (integer != 0) {
System.out.println("Please enter an integer(press zero to exit): ");
integer = input.nextInt();
if (integer > 0){
sum += integer;
count++;
if (integer > max)
max = integer;
if (integer < min)
min = integer;
}
}
System.out.println("The sum of your numbers is: " + sum);
System.out.println("Your count number is: " + count);
average = sum / count;
System.out.println("The average of your sum is: " + average);
System.out.println("The max integer is: " + max);
System.out.println("The min integer is: " + min);
}
}
You may try the below code
import java.util.Scanner;
public class ComputeDemo {
public static void main(String[] args) {
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
// double char1=0;
double min = integer;
double max = integer;
// char letter = 'q';
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer=input.nextInt();
if(integer>0)
{
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
else
{
min=0;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
}
}
}
}

Struggling to calculate average, min and max in java

I am currently struggling to calculate the average, minimum and maximum in my coding. I am receiving a lot of errors and not sure as to what I am doing wrong. Sorry if I am not providing enough information, I will update my post if needed. Also, I would appreciate if you can explain as to why you used that code so that I can understand please. Thank you.
EDIT - What I want it to do is when the user enters a set of numbers and finished inputting numbers, I want it to display the average of the numbers the user inputted after the histogram as well as the maximum and minimum. I assumed I would have to use my count variable as well as my num variable but still struggling in implementing it.
Errors I am receiving are shown in my coding below within the lines of coding.
import java.util.Scanner;
public class Histogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[5000];
int num = 0;
int count = 0;
int total = 1;
int max = 0;
int min = 0;
System.out.println ("Enter students marks in the range 0 to 100\n");
loop: for (count = 0; count <= total; count++)
{
System.out.println ("Enter a number:");
num = scan.nextInt();
if (num < 0 || num > 100)
{
break loop;
}
array[count] = num;
total = count+1;
}
System.out.println ("How many times a number between 0-100 occur.");
String[] asterisk = {"0- 29 | ", "30- 39 | ","40- 69 | ", "70- 100 | "}; //4 strings
for (count = 1; count <= total; count++)
{
num=array[count];
if (num >=0 && num <=29) asterisk [0] +="*";
else if (num>29 && num <=39) asterisk[1] +="*";
else if (num>39 && num <=69) asterisk[2] +="*";
else if (num>69 && num <=100) asterisk[3] +="*";
}
for (count =0;count < 4;count++)
System.out.println(asterisk[count]);
System.out.println("The total amount of students is " + total);
**int cannot be dereferenced** for (int i = 0; i < count.length; i++) {
**array required, but int found** num += count[i];
**array required, but int found** if (min > num[i]) {
**array required, but int found** min = num[i];
}
**array required, but int found** if (max < num[i]) {
**array required, but int found** max = num[i];
}
}
**int cannot be dereferenced** double average = (double) num / count.length;
System.out.printf(" min: " + min);
System.out.printf("%n max: " + max);
System.out.printf("%naverage: %.1f", average);
}
}
If you have an array, minimum is often calculated by first setting the initial minimum value to a known maximum value "infinity" or in this case 100. Next step would be to iterate over your set of values and check whether a value is below current minimum, and if so set minimum to that value.
int min = 100;
for (int i = 0; i < total; i++) {
if (array[i] < min) {
min = array[i];
}
}
for maximum, do the other way around, setting initial maximum value to 0 or negative "infinity" and check whether a value in the array is greater than current maximum value.
for average, sum all values and divide the result on the total amount of elements in the array.
int sum = 0;
for (int i = 0; i < total; i++) {
sum += array[i];
}
double avg = (double) (sum) / total;
In java positive infinity as integer type is represented as Integer.MAX_VALUE and negative infinity: Integer.MIN_VALUE.
Let's assume we have an array of values: int[] values = { some values }
To calculate average:
loop through the array and calculate the sum
divide sum by number of elements
int sum = 0;
for(int i : values) {
sum += i;
}
double average = (double)(sum) / values.length;
To find min and max:
loop through the array and compare current element with min and max and set them appropriately
int max = -2147483648; //set to min int value, -2^31
int min = 2147483647; //set to max int value, 2^31 - 1
for (int i : values) {
if (i > max) max = i;
if (i < min) min = i;
}
I see that the other posts have already answered how to calculate average, min, and max in an array, so I will only be tackling the error with your code.
You receive an error that says that int cannot be dereferenced:
tmp.java:48: int cannot be dereferenced
for (int i = 0; i < count.length; i++) {
^
This stems from the fact that you have defined count as an int not as an array. In fact, all of the compiling errors come from here. The variable count will not have a length, nor can you access its elements (it has none). In the last part of your code (where the errors arise) you have confused count, min, and max as arrays, whereas they are actually just integers. Your code was close (had the proper idea), but I think you might have confused some of the syntax.
Because your array length is always 5000, I had to use the second for loop to calculate the minimum number. Otherwise, if I was to use the first for loop (that is now commented), the minimum number would always be 0 (if less than 5000 numbers inputted) because there would always be trailing elements that are = 0. I would suggest using an ArrayList instead, but my code for you uses the same array you created.
I commented everything I changed/added from your code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[5000];
int num = 0;
int count = 0;
int total = 0; // start this at 0, in case no inputs are valid
double sum = 0; // make this a double to get a decimal average
int max = 0; // start at the lowest possible number for max
int min = 100; // start at the highest possible number for min
double average = 0;
System.out.println ("Enter students marks in the range 0 to 100\n");
loop: for (count = 0; count <= total; count++)
{
System.out.println ("Enter a number:");
num = scan.nextInt();
if (num < 0 || num > 100 || total == 5000) // can't enter more than 5000 (array length restriction)
{
break loop;
}
array[count] = num;
sum += num; // keep track of the sum during input
total = count+1;
}
System.out.println ("How many times a number between 0-100 occur.");
String[] asterisk = {"0- 29 | ", "30- 39 | ","40- 69 | ", "70- 100 | "}; //4 strings
for (count = 1; count <= total; count++)
{
num=array[count];
if (num >=0 && num <=29) asterisk [0] +="*";
else if (num>29 && num <=39) asterisk[1] +="*";
else if (num>39 && num <=69) asterisk[2] +="*";
else if (num>69 && num <=100) asterisk[3] +="*";
}
for (count =0;count < 4;count++)
System.out.println(asterisk[count]);
System.out.println("The total amount of students is " + total);
// calculate the average
average = sum / total;
// calculate the min and max
// use this for loop if the length of the array is
// the amount of the inputs from the user
/*for (int i : array) // for every int in the array of inputted ints
{
if (i > max) max = i; // if this int in array is > the last recording max number, set the new max number to be this int
if (i < min) min = i; // if this int in array is < the last recording min number, set the new min number to be this int
}*/
for (int i = 0; i < total; i++) // for every inputted int ( < total so that you exclude the trailing elements that are = 0)
{
if (array[i] > max) max = array[i]; // if this int in array is > the last recording max number, set the new max number to be this int
if (array[i] < min) min = array[i]; // if this int in array is < the last recording min number, set the new min number to be this int
}
// my way of printing results
//System.out.println("\n Average: " + average);
//System.out.println("Max: " + max + "\n Min: " + min);
System.out.printf(" min: " + min);
System.out.printf("%n max: " + max);
System.out.printf("%naverage: %.1f", average);
}

How to return person with max sales in salesperson program- JAVA

Kind of confused by one part of my HW problem. It seems like it would be easy, but I can't put my finger on it. I am trying to return the salesperson with the max and min sales. I am confused on how to do that. Help would be much appreciated.
import java.util.Scanner;
public class Cray {
public static void main(String[] args){
final int SALESPEOPLE = 5;
int[] sales = new int[SALESPEOPLE];
int sum, maxperson, minperson;
int max = sales[0];
int min = sales[0];
Scanner scan = new Scanner(System.in);
//Fill the 5 element array of sales with the user's input
for (int i=0; i<sales.length; i++)
{
System.out.print("Enter sales for salesperson " + i + ": ");
sales[i] = scan.nextInt();
//Calculate the max and min sales
//How do I return the salesperson i with the the max and min sales?
if(sales[i] > max){
max= sales[i];
}
if(sales[i] < min){
min = sales [i];
}
}
System.out.println("\nSalesperson Sales");
System.out.println("--------------------");
sum = 0;
for (int i=0; i<sales.length; i++)
{
System.out.println(" " + i + " " + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
System.out.println("Average sales: " + sum/5);
//WHere I want to print the max salesperson.
System.out.println("Salesperson" + );
}
}
you can store the index count
declare and initialize two int variables before you start scanning the input:
int maxindex=Integer.MIN_VALUE,minindex=Integer.MIN_VALUE;
And then assign your array index to them like this:
if(sales[i] > max){
max= sales[i];
maxindex = i;
}
if(sales[i] < min){
min = sales [i];
minindex = i;
}
Now you can directly get the salesperson with max and min sale
System.out.println("Max sales person "+sales[maxindex]);
System.out.println("Min sales person "+sales[minindex]);
I used a very simple trick here by storing the array indexes.
This is very basic approach though there may be more optimized approach for it.
You can adjust your check for maximum
if(sales[i] > max){
max = sales[i];
maxPerson = i;
}
Define two more variables as:
int maxSalePersonIndex = 0;
int minSalePersonIndex = 0;
Update your if as:
if(sales[i] > max){
max= sales[i];
maxSalePersonIndex = i;
}
if(sales[i] < min){
min = sales [i];
minSalePersonIndex = i;
}
In the end, just print the values of maxSalePersonIndex and minSalePersonIndex
System.out.println("Salesperson index with max sale = " + maxSalePersonIndex);
System.out.println("Salesperson index with min sale = " + minSalePersonIndex);
Currently in your for-loop, you're storing the maximum and minimum sales, not the salespeople who attained those sales. Therefore, you should be storing i in max / min, as opposed to sales[i].
int max = 0, int min = 0
...
// in the for-loop
if(sales[i] > sales[max]){
max = i; // i.e. salesperson "i"
}
if(sales[i] < sales[min]){
min = i;
}
...
System.out.println("Max salesperson: " + max);
System.out.println("Min salesperson: " + min);

Categories