Finding Minimum, Maximum, Evens, Odds, and Average. Java - java

As the title stated, I am trying to find the maximum and minimum values, the amount of evens and odds numbers, and the average of all inputted numbers.
The problem. As I run my code, my odds and evens counter seem to read their opposite, odd would read an even input and even would read an odd input. As for my average, I have no clue what is wrong with it, all I know is that it would only find the average of a proper fraction.
Example of my output will be pasted at the end.
import java.util.Scanner;
public class Homework7APrinter
{
public static void main (String[] args)
{
System.out.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner (System.in);
int min = Integer.MAX_VALUE;
int max = 0;
int count = 0;
int sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt = Integer.MIN_VALUE;
double average = 0;
boolean notnull = true;
while(scan.hasNextInt())
{
if(true)
{
if (getInt%2==1)
{
evensCounter++;
System.out.println("even: " + evensCounter);
}
else
{
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
getInt = scan.nextInt();
if(getInt < min)
{
min = getInt;
}
else if(getInt > max)
{
max = getInt;
}
}
else
{
notnull = false;
}
sum += getInt;
System.out.println("sum " +sum);
count++;
System.out.println("count " +count);
average = sum/(count);
System.out.println("average " +average);
}
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + oddsCounter);
System.out.println("odd: " + evensCounter);
System.out.println("average: " + average);
}
}
Result:
Enter a sequence of integers. Any non-integer to quit
1 //first input
odd: 1
sum 1
count 1
average 1.0
2 //second input
even: 1
sum 3
count 2
average 1.0
3 //third input
odd: 2
sum 6
count 3
average 2.0
4 //fourth input
even: 2
sum 10
count 4
average 2.0
q //quit the scan
smallest: 1
largest: 4
even: 2
odd: 2
average: 2.0 //average of 1, 2, 3, 4 = sum/n = 10/4 = 2.5 not 2.0
Any help would be appreciated. Thank you!

(getInt%2==1) is actually a check for odd number, it should be getInt%2==0 for even check

Few things-
Move getInt = scan.nextInt(); immediately after if(true) condition
For average make it - average = (double) sum / (count);
For even/odd issue make this change - if (getInt % 2 == 0)
So here's YOUR code with some clean up-
System.out.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = 0;
int count = 0;
int sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt;
double average = 0;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if (getInt % 2 == 0) {
evensCounter++;
System.out.println("even: " + evensCounter);
} else {
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
if (getInt < min) {
min = getInt;
} else if (getInt > max) {
max = getInt;
}
sum += getInt;
System.out.println("sum " + sum);
count++;
System.out.println("count " + count);
average = (double) sum / (count);
System.out.println("average " + average);
}
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + oddsCounter);
System.out.println("odd: " + evensCounter);
System.out.println("average: " + average);

This is what youre looking for
while(scan.hasNextInt())
{
getInt = scan.nextInt();
// if(true)
// {
if (getInt%2==0)
{
evensCounter++;
System.out.println("even: " + evensCounter);
}
else
{
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
//getInt = scan.nextInt();
if(getInt < min)
{
min = getInt;
}
else if(getInt > max)
{
max = getInt;
}
// }
// else
// {
// notnull = false;
// }
sum += getInt;
System.out.println("sum " +sum);
count++;
System.out.println("count " +count);
average = (double)sum/(count);
System.out.println("average " +average);
}

There were five mistakes in your program
You were printing incorrectly ( System.out.println("even: " + oddsCounter)). Even should be printed as evencounter
You have to make the sum also a double or float, to get the average in decimal format.
You have to read the getINT before you do the odd even test.
Even/odd calculation was wrong. it should be getInt%2==0
You should not have the if/else while calculating min and max. it should be two separate if's
Full working program below.
package com.stackoverflow.test;
import java.util.Scanner;
public class Homework7APrinter {
public static void main(String[] args) {
System.out
.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int count = 0;
double sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt = 0;
double average = 0;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if (getInt % 2 == 0) {
evensCounter++;
// System.out.println("even: " + evensCounter);
} else {
oddsCounter++;
// System.out.println("odd: " + oddsCounter);
}
if (getInt < min)
{
min = getInt;
}
if (getInt > max)
{
max = getInt;
}
sum += getInt;
// System.out.println("sum " +sum);
count++;
// System.out.println("count " +count);
average = sum / (count);
// System.out.println("average " +average);
}
System.out.println("*****************");
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + evensCounter);
System.out.println("odd: " + oddsCounter);
System.out.println("average: " + average);
System.out.println("sum: " + sum);
System.out.println("count: " + count);
}
}

Related

Is there perhaps a way of finding the above and below average

I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}
This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}
Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}
You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}
Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}

Difficulty to repeat an entire loop with string in Java

I am new to programming and I started to practice with Java. In my exercice, im asked to write a program which calculates and prints out the sum of the digits of a number. Then it prints out all the divisors of the sum number.
The problem is that after that, i need to ask the user if they want to try another number and im not able to restart the program when the person answer "yes" . Thank you and sorry for my english !
//Introduction
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
}
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
String choice = mykeyboard2.nextLine();
if (choice.equals("yes")) {
System.out.println("Enter a number with a most 7-digits:");
while (input > 0);
int add = input % 10;
sum = sum + add;
input = input / 10;
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++)
if (sum % counter == 0)
System.out.print(counter + " ");
} if (choice.equals("no")) {
System.out.println("Thanks and Have a Great Day!");
You just have to make it so the loop restarts
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
while(input != -1){
int sum = 0;
int add = input % 10;
sum = sum + add;
input = input / 10;
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.print("Do you want another number? If you dont type -1: ");
input = mykeyboard.nextInt();
}
The code will keep going until the user types -1
The easiest way is to implement it is using your choice variable to control a loop condition:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
String choice = "yes";
while(choice.equals("yes")) {
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
choice = mykeyboard2.nextLine();
}
System.out.println("Thanks and Have a Great Day!");
while (input > 0);
This will go in an infinite loop. I think you put a ; instead of {.
Should be while (input > 0){
EDIT:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
while(true){
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
}
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
String choice = mykeyboard2.nextLine();
if (choice.equals("no")) {
break;
}
}

This program should ask user for the max num to print out to and then calculate each number starting from 1 to the maximum along with it squared

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());

Calculate average of user input using for each

Hi Im new to java and trying to do some exercises to familiarize myself with it. I am trying to calculate the sum and average of the user input numbers using a for each or enhanced for loop. What i have done is to store the numbers in an array. Can you please check if my code is correct.
Scanner scanner = new Scanner(System.in);
double inputNum;
double sum= 0;
int counter;
System.out.println("How many entries would you like input");
int entry = scanner.nextInt();
for (counter = 0; counter< entry; counter++){
double [] numbers = new double[entry];
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
for (double x : numbers[counter]) {
x += sum;
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
}
You don't need the inner loop. You can add each input to the sum after you store it in the array.
In addition, you should allocate the array once outside the outer loop, and not in each iteration.
double [] numbers = new double[entry];
for (counter = 0; counter< entry; counter++){
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
sum+= numbers[counter];
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
Put the sum and average logic outside the loop. This should work:
double [] numbers = new double[entry];
for (counter = 0; counter< entry; counter++){
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
sum += numbers[counter];
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
You can't use a for-each with a scanner. Also there is no need your you to be storing anything. Just keep track of the sum.
Scanner scanner = new Scanner(System.in);
System.out.println("How many entries would you like input?");
int numEntries = scanner.nextInt();
double sum = 0;
for (counter = 1; counter <= numEntries; counter++) {
System.out.println("Please input number " + counter + ": ");
sum += scanner.nextDouble();
}
System.out.println("The total sum is: " + sum);
System.out.println("The average is: " + sum / numEntries);
Same code, with average outside the loop and the useless array removed:
Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.println("How many entries would you like input");
int entry = scanner.nextInt();
for (int counter = 1; counter <= entry; counter++) {
System.out.println("Please input number " + counter);
sum += scanner.nextDouble();
}
System.out.println("The total sum is: " + sum);
double average = sum / entry;
System.out.println("The total average is: " + average);

Combine for and while loop (Java)

I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}

Categories

Resources