how to exclude negative numbers from average calculation in while loop - java

I have a program that accepts user inputs and calculate Max, Min, and Average. The program closes when the user inputs any negative number. How do i exclude the negative number from the average calculation? Here is what i have so far.
// variable
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE ;
int count = 0;
double neg;
//creat scanner object
Scanner input = new Scanner(System.in);
//loop
while (n > 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
sum = sum + n;
count++;
ave = sum / count;
if(n<0) neg = n;
if(n>max && n >= 0 ) max = n;
if(n<min && n >= 0) min = n;
if(n>0) ave = n; }
System.out.print(" Average " + ave + "\n Maximum " + max + "\n Minimum " + min);
}
}

Add an if condition:
n = input.nextDouble();
if(n < 0)
break;
sum = sum + n;

The following code only sums the input numbers when n is not negative.
import java.util.Scanner;
public class sample {
public static void main(String[] args) {
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
int count = 0;
double neg;
Scanner input = new Scanner(System.in);
// loop
while (n > 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
if(n >= 0){
sum = sum + n;
count++;
}
if (n < 0)
neg = n;
if (n > max && n >= 0)
max = n;
if (n < min && n >= 0)
min = n;
if (n > 0)
ave = n;
}
System.out.print(" Average " + ave + "\n Maximum " + max
+ "\n Minimum " + min);
}
}

Try this:
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE ;
int count = 0;
// create scanner object
Scanner input = new Scanner(System.in);
// loop until n is negative
while (n >= 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
if (n >= 0) {
if (n > max) max = n;
if (n < min) min = n;
sum = sum + n;
count++;
}
}
if (count > 0)
ave = sum / (double) count;
System.out.print(" Average " + ave + "\n Maximum " + max + "\n Minimum " + min);

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.

max min ODD numbers from a sequence without arrays

I am trying to get the max and min ODD numbers from sequence of inputs without using an array, please advise what should I add, I am using the below code:
System.out.print("Enter odd integers(even to Stop): " );
do {
num = input.nextInt();
sum += num;
} while (num % 2 != 0);
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
System.out.print("Minimum Odd Number: " + min + ";");
System.out.println("Maximum Odd Number: " + max);
System.out.print("Sum: " + sum);
Your logic to check the odd value, to possibly record it as a min or max, should be inside the loop:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int num = input.nextInt();
while (num % 2 != 0) {
sum += num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
num = input.nextInt();
}
System.out.print("Minimum Odd Number: " + min + ";");
System.out.println("Maximum Odd Number: " + max);
System.out.print("Sum: " + sum);
As a comment, I initialize the min and max integers to the largest and smallest integer values, respectively. This ensures that we correctly capture the very first inputs, whatever they might be.
This will work. If there aren't any odd numbers given min and max will be 0:
Scanner input = new Scanner(System.in);
int num = 0, sum = 0, max = 0, min = Integer.MAX_VALUE;
System.out.print("Enter odd integers(even to Stop): ");
do {
num = input.nextInt();
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
sum += num;
} while (num % 2 != 0);
if(min % 2 == 0) min = 0;
if(max % 2 == 0) max = 0;
System.out.print("Minimum Odd Number: " + min + ";");
System.out.println("Maximum Odd Number: " + max);
System.out.print("Sum: " + sum);
input.close();

How to understand why this does not return the minimum value?

Please help to understand why, in the following, I didn't get output of minimum value in array. Using scanner for input value, the program should output also the minimum number.
** without using .sort.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);
}
}
I will suggest two improvements at the bare minimum.
Initialize your min to the first value. Right now you have min initialized to 0 and user never enters any number smaller than 0. That's why you keep getting 0 for min.
Don't run your loops 1000 times. Run it as many times as there are non zero elements.
See the following working snippet:
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
min = value;
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length && list[i] !=0; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);

Do-while or while loop to use math.random to generate a set of 20 numbers

What I'm trying to do is generate a set of 20 different random numbers, then display the average, number of positive numbers and number of negative numbers. I'm stumped on generating the set of numbers to use, but I think I have everything else done right.
int positive = 0;
int negative = 0;
int count = 0;
int total = 0;
int average;
Random r = new Random();
int number = 0;
while (count > 20) {
number = r.nextInt(200);
total += number;
count++;
if (number > 0) {
positive++;
}
else if (number < 0) {
negative++;
}
}
average = (double) total / count;
System.out.println("The number of positives is " + positive + " ");
System.out.println("The number of negatives is " + negative + " ");
System.out.printf("The average is: " + average);
Here is a way for you to total up 20 random numbers from 0-100 and then display the result.
private int total = 0;
private int i = 0;
private Random generator = new Random();
private int pos = 0;
private int neg = 0;
private int max_int = Integer.MIN_VALUE;
private int min_int = Integer.MAX_VALUE;
private int x;
while(i < 20){
x = (int) int val = 100 - generator.nextInt(200);
if(x > max_int)
max_int = x;
if(x < min_int)
min_int = x;
if(x >= 0)
pos ++;
else
neg ++;
total += x
i++;
}
System.out.println(total / 20.0);
System.out.println("Positive number count :: " + pos);
System.out.println("Positive number count :: " + neg);
System.out.println("Max :: " + max_int);
System.out.println("Min :: " + min_int);

Find largest and smallest numbers number using Arrays

Trying to let users enter number of integers so I can set array length then find the max and min value. However, I can't find max and min. Please help.
import java.util.Scanner;
import java.util.Arrays;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
System.out.println("Enter some integers:");
int integers = keyboard.nextInt();
int numbers [] = new int [numberEnter];
int maxValue = numbers[0];
int minValue = numbers[0];
int max = 0;
int min = 0;
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
You don't seem to be entering more then one value (and you never store integers in your array). Also, you aren't setting the min. I think you wanted
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of integers to enter:");
int numberEnter = keyboard.nextInt();
int numbers[] = new int[numberEnter];
int pos = 0;
do {
System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
numbers[pos++] = keyboard.nextInt();
} while (pos < numberEnter && keyboard.hasNextInt());
int min = numbers[0];
int max = numbers[0];
for (pos = 1; pos < numbers.length; pos++) {
if (numbers[pos] < min) { // <-- test min.
min = numbers[pos];
}
if (numbers[pos] > max) { // <-- test max.
max = numbers[pos];
}
}
// Display everything.
System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
min, max);
}
Your numbers[] is empty. The user's input is not stored into the array.
Here is your fixed code:
package com.company;
import java.util.Scanner;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
int numbers [] = new int [numberEnter];
for (int i = 0; i < numberEnter; i++) {
System.out.println("Enter integer:");
numbers[i] = keyboard.nextInt();
}
int maxValue = numbers[0];
int minValue = numbers[0];
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
import java.util.Scanner;
class StdR {
public static void main(String[] args) {
// TODO Auto-generated method stub
StdR st = new StdR();
st.stdR();
//System.out.println(st.stdR();
}
void stdR()
{
char[] grade = {'A','B','C','D','E','F'};
Scanner input = new Scanner(System.in);
byte[] st = new byte[3];
double[] percentage = new double[st.length];
for(byte s = 0; s < st.length; s++){
System.out.println("\nStudent " + s);
short noOfMarks = 0;
short totalMarks = 450;
percentage[s] = 0.0;
byte[] marks = new byte[5];
for (byte i = 0; i < marks.length; i++){
System.out.println("Enter marks of Chapter "+ i + ": ");
marks[i] = input.nextByte();
noOfMarks += marks[i];
percentage[s] += (marks[i] * 100) / totalMarks;
}
System.out.print("No of marks: " + noOfMarks + "\t");
System.out.print("Percentage: " + percentage[s] + "\t");
if (percentage[s] > 79.0 && percentage[s] < 100.1)
System.out.print("Grade: " + grade[0]);
else if (percentage[s] > 69.0 && percentage[s] < 80.0)
System.out.print("Grade: " + grade[1]);
else if (percentage[s] > 59.0 && percentage[s] < 70.0)
System.out.print("Grade: " + grade[2]);
else if (percentage[s] > 49.0 && percentage[s] < 60.0)
System.out.print("Grade: " + grade[3]);
else if (percentage[s] > 39.0 && percentage[s] < 50.0)
System.out.print("Grade: " + grade[4]);
else if (percentage[s] < 40.0)
System.out.print("Grade: " + grade[5]);
}
double smallest = percentage[0] , largest= percentage[0];
for (int i=0 ;i< percentage.length; i++) {
if (percentage[i] < smallest) {
smallest = percentage[i];
} // end finding smallest
if (percentage[i] > largest) {
largest = percentage[i];
}
}
System.out.println("\n1st Position and Top percentage is " + largest);
System.out.println("\nLast Position and Least percentage is "+smallest);
}
}

Categories