I am trying to get the sum, average, max and min value from user input in array. sum, average and max is giving the correct output. But min value is not working. Where am I doing wrong would someone help me please to find out?
import java.util.Scanner;
public class minMaxSumAverage {
public static void main(String args[]) {
int n, sum = 0, max, min;
double average = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
n = s.nextInt();
int a[] = new int[n];
max = a[0];
min = a[0];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum += a[i];
average = (double) sum/a.length;
if (a[i] > max) {
max = a[i];
}
if (a[i] < min) {
min = a[i];
}
}
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}
Output:
Enter elements you want to input in array:
5
Enter all the elements:
25
5
10
6
4
Sum is: 50
Average is: 10.0
Max is: 25
Min is: 0
Min value should be 4.
I have updated you code. Please check following code to get min value from all element list.
Input :
Enter elements you want to input in array:
5
Enter all the elements:
25
5
10
6
4
Output :
Sum is: 50
Average is: 10.0
Max is: 25
Min is: 4
Scanner scan = null;
try {
int n, sum = 0, max, min;
double average = 0;
scan = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
n = scan.nextInt();
int a[] = new int[n];
max = a[0];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = scan.nextInt();
sum += a[i];
average = (double) sum/a.length;
if (a[i] > max) {
max = a[i];
}
/**
// from here remove logic for get min value.
if (a[i] < min) {
min = a[i];
}
**/
}
min = a[0];
for(int i=0;i<a.length;i++){
if(a[i] < min){
min = a[i];
}
}
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
catch (Exception ex) {
ex.printStackTrace();
}finally{
scan.close();
}
From Java-8 you can use streams to get this done in single line:
int[] a = new int[] { 20,11,2,3,4,7,8,90 };
int min = Arrays.stream(a).min().getAsInt();
for getting the maximum element, just replace the .min() with .max()
for getting sum: Arrays.stream(a).mapToInt(Integer::intValue).sum();
Because min is initialized with 0.
And in your loop you just ask if your current number is smaller than 0.
Try again with assigning the first value of your array as min.
Then it should work.
int a[] = new int[n];
max = a[0];
min = a[0];
You have created an empty array a. Both max and min are initialized to 0. This works fine for max, but gives you the result you are seeing for min, because there is nothing smaller in your created array than zero.
To fix this, add your line min = a[0]; into the for loop after you have filled up your array with values, e.g.
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum += a[i];
average = (double) sum/a.length;
min = a[0];
//if-statements here
Then, min = a[0] will no longer be zero, but will be the first value of the filled up array.
Please refer below code for a min, max, sum, average functionality :
List<Integer> intList= Arrays.asList(70, 80, 10, 20, 40, 50);
Integer ans=0;
int sum1= intList.stream().reduce(ans, (x,y) -> x+y);
System.out.println(sum1);
int sum2= intList.stream().reduce(ans, Integer::sum);
System.out.println(sum2);
int max= intList.stream().max(Integer::compare).get();
System.out.println(max);
int min= intList.stream().min(Integer::compare).get();
System.out.println(min);
Double avg= intList.stream().collect(Collectors.averagingInt(x-> x));
System.out.println(avg);
As an alternative, you may want to consider a Stream...
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter count elements you want to input in array: ");
int n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
s.close();
IntSummaryStatistics iss = Arrays.stream(a).summaryStatistics();
System.out.println("Sum is: " + iss.getSum());
System.out.println("Average is: " + iss.getSum()/iss.getCount());
System.out.println("Max is: " + iss.getMax());
System.out.println("Min is: " + iss.getMin());
}
Related
The code displays the sum, average, and largest element. It doesn't display the smallest element as the output is always zero. How do I display the smallest element in the array?
import java.util.Scanner;
public class Average {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int length = input.nextInt();
int[] num = new int[length];
System.out.println("Enter the "+ length + " array elements:");
int sum = 0;
int large,small;
large =small = num[0];
for (int i=0; i<length;i++) {
num[i] = input.nextInt();
sum = sum+ num[i];
}
for (int i=0; i<length; ++i) {
if (num[i]<small) {
small = num[i];
}
if(num[i]> large) {
large = num[i];
}
}
double avg = sum/length;
System.out.println("The sum is "+ sum);
System.out.println("The average is "+ avg);
System.out.println("The smallest element is "+ small);
System.out.println("The largest element is "+ large);
}
}
import java.util.Scanner;
class Average {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int length = input.nextInt();
int[] num = new int[length];
System.out.println("Enter the " + length + " array elements:");
int sum = 0;
int large, small;
for (int i = 0; i < length; i++) {
num[i] = input.nextInt();
sum = sum + num[i];
}
large = small = num[0]; // small should be assigned after num is input
for (int i = 0; i < length; ++i) {
if (num[i] < small) {
small = num[i];
}
if (num[i] > large) {
large = num[i];
}
}
double avg = sum / length;
System.out.println("The sum is " + sum);
System.out.println("The average is " + avg);
System.out.println("The smallest element is " + small);
System.out.println("The largest element is " + large);
}
}
Yea, it's happening because by default your field small is equal to 0.
And now let's look step by step your if statement
if (num[i]<small) {
small = num[i];
}
example for numbers: 22,11,6,
So first step is num[0] < 0, why 0 as mention before small = 0 by default
Step two num[1] < 0, small stills stay 0
Step Three num[2] < 0, small stills stay 0.
What are you missing, you need to assign value to small at the first iteration of your for loop, for example:
for (int i=0; i<length; ++i) {
if(i == 0){
small = num[i];
}
if (num[i]<small) {
small = num[i];
}
if(num[i]> large) {
large = num[i];
}
}
Now your program should work :)
if you use java 8 or above, you can use the stream method of Arrays. it simplifies work with arrays. for more info
firstly import the Arrays as import java.util.Arrays;
System.out.println("The sum is " + Arrays.stream(num).sum());
System.out.println("The average is " + Arrays.stream(num).average());
System.out.println("The smallest element is " + Arrays.stream(num).min());
System.out.println("The largest element is " + Arrays.stream(num).max());
I have some trouble when I try to code a program.
double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0
Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.
Your initial value for minimum is zero, and I assume your data has nothing that is less than zero.
Try setting your min initial value to Double.MAX_VALUE
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this :
double array[] = new double[10];
int i;
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
double max = array[0], min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Two simple corrections:
You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)
there is no need to 3 for loops to find the min and max, just use one.
see below code:
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();
double max = array[0], min = array[0];
for (i = 1; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
if(array[i] > max)
max = array[i] ;
if (array[i] < min)
min = array[i];
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Your curly braces are not proper. You are ending the max loop before the SYSOUT.
double max = 0, min = 0;
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
for (i = 0; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
}
max = array[0];
min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Run this. It will give the proper result.
package HW2_Min_Max;
import java.util.Scanner;
public class HW2_Min_Max {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Please input a positive interger that indicates number of positive intergers ");
int number = myScanner.nextInt();
while (number <= 0) {
System.out.println("Please input interger");
number = myScanner.nextInt();
}
int i=1; //i is to store current iteration
int sum=0; //sum is to store sum of the input
int x; //x is to store the user input
while (i <= number){
System.out.println("Please input a positive interger ");
x = myScanner.nextInt();
sum = sum + x;
i++;
}
int average = sum/number;
System.out.println("The average is " + average);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
if (number < min){
min = number;
}
if (number > max) {
max = number;
}
System.out.println("The minimum value is " + min);
System.out.print( "and the maximum value is" + max);
}
}
}
1.^ this is where i am getting my problem, on the very last brace in Netbeans i am getting an error that says "class, interface, or enum expected" but i have no idea why. Excuse my ignorance as I am a very fresh beginner with java, let alone programming.
For the first part, I would suggest you use a do-while loop to test for the number of numbers. Like,
int number;
do {
System.out.println("Please input a positive integer that "
+ "indicates number of positive integers ");
number = myScanner.nextInt();
} while (number <= 0);
Then you need to set min and max in your loop (or store all the values you read). I would prefer Math.max and Math.min. I would also count from 0. Like,
int i = 0; // i is to store current iteration
int sum = 0; // sum is to store sum of the input
int x; // x is to store the user input
int max = Integer.MIN_VALUE; // store the max user input
int min = Integer.MAX_VALUE; // store the min user input
while (i < number) {
System.out.println("Please input a positive integer ");
x = myScanner.nextInt();
if (x > 0) { // make sure it's a positive integer
min = Math.min(min, x);
max = Math.max(max, x);
sum += x;
i++;
}
}
int average = sum / number;
System.out.println("The average is " + average);
System.out.println("The minimum value is " + min);
System.out.println("and the maximum value is " + max);
Its working fine now. I have made some changes in it. Kindly consider it. I hope it would help.
Scanner myScanner = new Scanner(System.in);
System.out.println("Please input a positive interger that indicates number of positive intergers ");
int number = myScanner.nextInt();
while (number <= 0) {
System.out.println("Please input interger");
number = myScanner.nextInt();
}
int[] arr = new int[number]; // Store values in array
int i=0; //i is to store current iteration
int sum=0; //sum is to store sum of the input
int x; //x is to store the user input
int max = 0;
int min = 0;
for(i=0;i<number;i++){
System.out.println("Please input a positive interger ");
arr[i] = myScanner.nextInt();
sum = sum + arr[i];
}
int average = sum/number;
System.out.println("The average is " + average);
// Put initial values in min and max for comparing
min =arr[0];
max = arr[0];
for(i=1;i<number;i++)
{
// Compare if values is less than arr[i]
if (arr[i] < min){
min = arr[i];
}
// Compare if values is greater than arr[i]
if (arr[i] > max) {
max = arr[i];
}
}
System.out.print("The minimum value is " + min);
System.out.println( " and the maximum value is " + max);
}
}
Here is the output:
I have an assignment where I am supposed to have 6 elements in an integer array and program supposed to find the highest and lowest element in an array and omit those two elements and find the average for the remaining four elements. So far my program is able to find the lowest and highest number in that array and able to omit it, however, I cant seem to save those results from the loop to a variable so I can start to calculate my average. the code is
int bucky[] = { 4, 6, 8, 19, 199, 400 };
int hello = 0;
int max = 0;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] > max) {
max = bucky[i];
}
}
System.out.println("Max number is " + max);
int min = 0;
int j = 1;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] < bucky[j]) {
min = bucky[i];
j = i;
}
}
System.out.println("min number is " + min);
System.out.print("{");
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] != max) {
if (bucky[i] != min) {
System.out.print(" " + bucky[i]);
}
}
}
System.out.print("}");
So far it prints out {6 8 19 199}. I want to be able to save them in a variable and calculate the average. Any help would be appreciated.
Here is a simple program that might achieve what you are after.
What should happen if all elements have the same value?
int[] input = {0,1,2,3,4,5};
int max = input[0];
int min = input[0];
int sum = 0;
for(int i : input){
sum += i;
if(i < min){
min = i;
}else if(i > max){
max = i;
}
}
System.out.println("sum for input is : " + sum);
System.out.println("highest value element is : " + max);
System.out.println("lowest value element is : " + min);
System.out.println("sum excluding extreme elements is : " + (sum - min -max));
// have cast the result as a float as i dont know if average should be truncated or not
System.out.println("average excluding extreme elements is : " + ((float)(sum - min -max)/(input.length-2)));
public static void main(String args []){
int bucky [] = new int [] {4, 6, 8, 19, 199, 400};
int max = bucky[0];
int min = bucky[0];
int sum = 0;
for(int i = 0; i<bucky.length; i++){
if(min > bucky[i]){
min = bucky[i];
}
else if(max < bucky[i]){
max = bucky[i];
}
sum += bucky[i];
}
sum -= (min + max);
System.out.println("Max is " + max);
System.out.println("Min is " + min);
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum/(bucky.length-2));
}
Small program can be developed using arrays in Java as follows, which initially stores very first element of the array in min, max, and sum, then start traversing the array from first element and determine min and max value elements by comparing them with the current element pointed by input[i] of the array. Also add input[i] every time to the sum variable to get sum of all elements. After having computed min, max, and sum value elements; compute avg by subtracting min and max from sum and divide the resultant value by length - 2.
class ComputeAvg
{
public static void main (String[] a)
{
int[] input = {10,11,12,13,14,15};
int min, max, sum, avg;
min = max = sum = input[0];
int length = input.length;
for (int i = 1; i < length; i++)
{
if (min > input[i])
min = input[i];
else if (max < input[i])
max = input[i];
sum += input[i];
}
avg = (sum - min - max)/(length - 2);
System.out.println("sum for input is : " + sum);
System.out.println("highest value element is : " + max);
System.out.println("lowest value element is : " + min);
System.out.println("sum excluding min and max value elements is : " + (sum - min - max));
System.out.println("Average after excluding min and max value elements is : " + avg);
}
}
OUTPUT
======
sum for input is : 75
highest value element is : 15
lowest value element is : 10
sum excluding min and max value elements is : 50
Average after excluding min and max value elements is : 12
You're 90% there. You just need a nudge in the right direction.
You already know how to filter your results from highest and lowest with this statement (rewritten to compress nested ifs):
for(int i=0;i<bucky.length; i++){
if(bucky[i] != max && bucky[i] !=min) {
// implementation
}
}
By the way, it can be rewritten as this, thanks to De Morgan's Law. This may read more straightforward for you: "If the value in bucky[i] is neither max nor min..."
for(int i=0;i<bucky.length; i++){
if(!(bucky[i] == max || bucky[i] ==min)) {
// implementation
}
}
That was the hard part. What you now need:
A counter to tell you how many values you actually are adding. Something like adjustedTotal. You'd only ever add to this counter if the number wasn't the min or the max.
A simple sum variable, initialized appropriately, taking the values from bucky[i] such that bucky[i] != max && bucky[i] != min.
int sum=0;
for (int i=0 ;i< arr.length;i++) {
if(arr[i]!=max && arr[i]!=min) {
sum=sum+arr[i];
}
}
int average=sum/(arr.length-2)
You can define an variable named sum like Makoto mentioned above.
In additional, I would like to point out that there is something wrong with your code for calculating min.
Here is an example,
Assume the int[] array is as follows:
int bucky[] = { 6, 4, 8, 19, 400,199 };
Use your code below:
int min = 0;
int j = 1;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] < bucky[j]) {
min = bucky[i];
j = i;
}
}
System.out.println("min number is " + min);
What will be the value for min ?
It will be 0. It is incorrect.
You can first specify the first element in array as min, and then compare it with remaining values. If any value is smaller than min, then change the value for min.
Here is an example:
int min = bucky[0];
//int j = 1;
for (int i = 1; i < bucky.length; i++) {
if (bucky[i] < min) {
min = bucky[i];
}
}
System.out.println("min number is " + min);
Make some change and move on. :)
I just found that when I calculate the average for the second user, I get a different result. For example, if I add this number for the first user 10,10,10,20,20. I get 14.0 which is correct. But when I enter the same number for the second user I get 28.0? any ideas?
import java.util.Scanner;
public class midterm
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
double average=0;
int count = 0;
int salary_annually = 0;
for(int employee =1; employee <= 2; employee++)
{
System.out.println("Employee: " + employee);
for(int year=1; year <= 5; year++)
{
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually ;
average = (sum) / 5.0;
if (min >= salary_annually)
{
min = salary_annually;
}
if (max <=salary_annually)
{
max = salary_annually;
}
}
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
sum = 0; // this before 2nd loop
int max = Integer.MIN_VALUE; // these too.
int min = Integer.MAX_VALUE;
for(int year=1; year <= 5; year++)
{
.
.
.
}
average = (sum) / 5.0; // this after 2nd loop
In your solution you are calculating average 5 times inside the loop! and you only get advantage from the fifth time! must be after the loop. average = (sum) / 5.0; after the loop.
You need to zero sum at the end of the loop. As it is, now it just keeps increasing and increasing as the old value is kept in memory, when coming to the next iteration.