min max in array issue - java

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.

Related

Java - How to only count the inputted positive numbers

I am trying to find sum and averags of user inputed numbers and i also Need my program to only sum the positive numbers entered.
It needs to calculate only the positive numbers sum and ignore the negative inputs, would i put my num=0 or not?
import java.util.Scanner;
public class J12ForSumPos {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int maxNumbers, i, num, average;
int sum = 0;
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for (i = 1; i <= maxNumbers; i = i + 1) {
System.out.print("Enter Value " + i + ": ");
num = console.nextInt();
sum = sum + num;
}
average = sum / maxNumbers;
if (sum >= 0) {
System.out.println();
System.out.println("Sum: " + sum);
System.out.println();
System.out.println("Average: " + average);
System.out.println();
} else {
System.out.println("Sum is: " + sum * 0);
System.out.println();
System.out.println("Cannot Calculate Average - no positives entered");
}
}
}
You can try something like this:
Scanner console = new Scanner(System.in);
int maxNumbers = 0;
int totalSum = 0; // Sum of all numbers (positive and negative)
int totalAverage = 0; // Average of all numbers (positive and negative)
int positiveSum = 0; // Sum of all positive numbers
int positiveAverage = 0; // Average of all positive numbers
int positiveNumberCount = 0; // Amount of positive numbers entered
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for(int i=1; i<=maxNumbers; i=i+1)
{
System.out.print("Enter Value " + i + ": ");
int num = console.nextInt();
if(num >= 0) {
positiveSum = positiveSum + num;
positiveNumberCount = positiveNumberCount + 1;
}
totalSum = totalSum + num;
}
positiveAverage = positiveSum / positiveNumberCount;
totalAverage = totalSum / maxNumbers;
It's up to you to decide whether or not to include 0 as a positive or a negative number, or exclude it. In my example it's being treated as a positive number.

Finding the lowest value in the array

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.

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("");
}
}
}
}

I can't find max and min

I want to create program read more than 10 numbers from the user and find the maximum number and minimum number then print all the numbers from the user.
This is my program, but I don't know how can I find the maximum number and minimum number:
import java.io.*;
public class ass3 {
public static void main (String [] args) throws IOException
{
int times , num1 ;
int max , min;
System.out.print("How many numbers you want to enter?\n*moer than five number");
times=IOClass.getInt();
if (times>5) {
for(int i = 0;i<times;i++){
System.out.println("please type the "+i+ "number");
num1=IOClass.getInt();
}
}
}
}
If you initialize the min and max like this:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
You can check whether the new number is smaller than min or bigger than max, and change them if needed:
int num = ...;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
This is my solution, hope it helps:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to enter?\nThe number must be grater than 5");
int times = in.nextInt();
if (times > 5)
{
int[] numbers = new int[times];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < times; i++)
{
System.out.println("Please type the " + i + " number:");
int number = in.nextInt();
numbers[i] = number;
if(number < min)
{
min = number;
}
if(number > max)
{
max = number;
}
}
System.out.println("Max: " + max);
System.out.println("Min: " + min);
}
in.close();
}
}

Getting the lowest and highest value from integers without using arrays?

I'm trying to write a class which reads 5 integers from the user and returns the highest and lowest value back. This must be done using loops and without using arrays and Integer.MIN.Value/Integer.MAX.Value. I've already succeeded writing code that gets 5 integers from the user and returns the highest value but I just can't get both the highest and the lowest value returned in the same class.
Here is the code I mentioned above:
import java.util.Scanner;
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;
for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (number > max){
max = number;
}
}
System.out.println("Highest value: " + max);
}
}
here you go :)
import java.util.Scanner;
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int min = 0;
for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (x == 0 || number > max){
max = number;
}
if (x == 0 || number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}
Why not just repeat your max logic for min?
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Give me an integer: ");
number = input.nextInt();
int max = number;
int min = number;
for (int x = 0; x<4; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (number > max){
max = number;
}
if (number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}
Note that max and min are initially set to the first number that the user enters, so there will be no false 0's and no need to MAX_INT or MIN_INT. This in turn makes the loop run once less so terminate at i == 4 instead of 5.

Categories