Subtracting 1 from count before getting average - java

Below is a code I have written to give me the largest and smallest integer while also finding the average of the integers entered. My problem is that it is counting the negative number when finding the average. I need it to not count the negative number. Maybe subtracting one from the count? Or an if else statement?
import java.util.Scanner;
public class LargeSmallAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int smallest, largest, sum, count;
sum = 0;
count = 0;
System.out.println("Please enter a series of positive numbers. Enter a negative number to exit program.");
int positive = in.nextInt();
smallest = largest = positive;
while (positive > 0)
{
if (smallest > positive)
smallest = positive;
if (largest < positive)
largest = positive;
sum = sum + positive;
count++;
positive = in.nextInt();
}
double average = sum / count;
System.out.println("The smallest number entered was " + smallest);
System.out.println("The largest number entered was " + largest);
System.out.println("The average of all positive numbers entered is " + average);
}
}
OUTPUT:
Please enter a series of positive numbers. Enter a negative number to exit program.
2
20
10
5
10
2
-5
The smallest number entered was 2
The largest number entered was 20
The average of all positive numbers entered is 8.0

double average = ((double) sum) / count;
You used integer division 49 / 6 = 8.

Related

A Java program with a loop that allows the user to enter a series of integers, then displays the smallest and largest numbers + the average

I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.

Why doesn't the scanner class recognize the other numbers?

public class Hello {
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
}
I would like to get the expected output given below. But, the Scanner class is reading only the first number. How do I correct this without creating multiple objects?
Output:
2
-1
-5
-3
9
8
0
The largest integer is 2
The number of negative integers in the sequence is 0
The largest even integer in the sequence is 2
The sum of numbers divisible by 3 is 0
Process finished with exit code 0
expected Output:
The largest integer is 9
The number of negative integers in the sequence is 3
The largest even integer in the sequence is 8
The sum of numbers divisible by 3 is 6
Thank you!
You only call console.nextInt() once, so only one number is read. If you want to call you need to loop over calls to console.hasNext(). Since you're using System.in. E.g.:
while (console.hasNextInt()) {
number = console.nextInt();
// calculations
}
You are only reading input once. I don't see a loop in your code, so number = console.nextInt(); only runs once. What you should do is put it inside a loop, exit the loop when you have all the numbers (how you check that can be done in multiple ways), and while you're inside the loop put whatever input you receive into an array or another data structure. After you're done collecting input, do your checks over all the numbers on your data structure.
1- You must first receive the data from the user and then calculate it and generate the output. You can do this using the arrays and after finishing put your data, calculate on them.
for example :
private static final int DATA_SIZE = 5;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> data = new ArrayList<>();
// put data in array
while (data.size() == DATA_SIZE){
data.add(scanner.nextInt());
}
// calculate data from array ...
}
2- When you call a field like nextInt() Scanner class , it is done only once, then you put it in a loop to be repeated several times ...
Of course, I have other suggestions for doing this
For example, you can use the array available in the main method (with knowledge, of course)
OR
First ask the user for the amount of data you have, then take it and then calculate
OR....
If you want to type all number at once ,you should set a terminal number. when you input all you number,you shoud add the terminal number to indicate input is over.
For example:
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
int endNumber = -1; //set the terminal number
do {
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
}while (number!=endNumber);
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
The line if code is only being executed once. Thus, the Scanner is only taking in the first in put. Use a while loop to take in multiple inputs.

Java: How to infinitely enter numbers, stop when negative number is entered and computer the average

I am trying to write a Java program that takes in a potentially infinite number of values - and once the user enters a negative number, the program stops, computes the average of all of the entered numbers (excluding the negative one) and prints out how many numbers were entered (once again, not the negative one) as well as the average.
Below is the code I currently have. When I try to run the program, it does not computer the average correctly and you have to enter a couple consecutive negative numbers for it to finally stop the program.
To test the arithmetic and the rest of the program, I inserted a statement that would close the program if the word "negative" was entered rather than a negative number. When did this, the average and count and everything else worked just like it was made to. Essentially, the problems start to occur when I try to stop the program after a negative number.
I am a beginning programmer and this has been driving me crazy for a couple hours. Any help is greatly appreciated!
import java.util.*;
import java.lang.Math;
import java.io.IOException;
import java.io.InputStream;
public class Average
{
public static void main(String[] args)
{
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += numInput.nextDouble();
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
}
You should use: sum+=negNum; instead of sum += numInput.nextDouble();
As it is now, your program, reads a number and if it is not negative it reads another number and adds it to the sum.
Also, you should compute the average only once in the else block.
You are reading a new number to compute the sum.
It should be
sum += negNum;
You have already received the number entered by the user in line:
double negNum = numInput.nextDouble();
You should add this number itself to sum rather than asking for another number from user by calling numInput.nextDouble() again. So the fixed code would be:
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += negNum;
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
Sample Run:
Enter a series of numbers. Enter a negative number to quit.
2
3
-1
You entered 2.0 numbers averaging 2.5.
Change
sum += numInput.nextDouble(); // reading next value again
to
sum += negNum;

Count Positive and negative numbers

public class Exercise_442 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int count=0;
int positive=0;
int negative =0;
int nums=0;
int sum=0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Pleaes enter a positive or negative integer");
nums = keyboard.nextInt();
while(nums!=0){
sum+=nums;
System.out.println("Plese enter a positive or negative integer");
nums = keyboard.nextInt();
if(nums<0)
negative++;
if (nums>0)
positive++;
}
System.out.println("The sum of these numbers is " +sum);
System.out.println("The amount of negative numbers here is " + negative);
System.out.println("The amount of positive numbers here is " + positive);
}
}
I need to count the positive and negative numbers here when I enter them. It displays these when the user inputs 0. It counts the negative numbers ok and gets the sum but I don't know why it falls short of one number when it counts the positive integers?
Your first nums is ignored for +/- when you enter the while loop for the first time.
Let's say you enter 1 as nums. It'll add 1 to the sums and then ask for a new input without evaluating > or <.
Move your if statements above the nums = keyboard.nextInt(); in the while loop.
while(nums!=0){
sum+=nums;
//moved everything up before we pull nextInt
if(nums<0)
negative++;
if (nums>0)
positive++;
System.out.println("Plese enter a positive or negative integer");
nums = keyboard.nextInt();
}

JAVA do-while Loop doubles the output value

The following code outputs the sum, average, count of positive/negative numbers, count of all numbers correctly when ran first time. Because it loops, hence, the output remains on the console prompting user to enter numbers again. At this time, only sum shows the correct output, other values doubles. Please help me in fixing the loop. Thanks!
public class Test {
public static void main(String[] args) {
long n;
int count=0;
float average;
int positive=0;
int negative =0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a positive or negative integers: ");
n = in.nextLong();
if (n == 0){
System.out.println("Integers you've entered is invalid. Please re-launch the Program.");
}
else
{
int sum=0;
do
{
//Find sum of the integers entered.
sum += n %10;
n /= 10;
//Count number of integers entered.
count++;
//Find average of the numbers
average = sum / count;
//Find a count of positive and negative numbers.
if(n < negative){
negative++;
}
else{
positive++;
}
} while (n != 0);
n = sum;
System.out.println("The Sum of the numbers: " + sum);
System.out.println("The Average of the numbers: " + average);
System.out.println("Positive numbers are: " + positive);
System.out.println("Negative numbers are: " + negative);
System.out.println("The count of all numbers: " +count);
}
} while(n != 0);
}
}
It would make sense that sum is the only one that outputs correctly; It's the only value you initialize every iteration of your outer loop.
the values count, positive, and negative aren't re-initialized each iteration, so when you begin the next iteration of your outer loop, they will start from wherever they printed as.
you might want to initialize them again every time you run the loop.
You never reinitialize your variables before entering in your do while loop for a second time.
So
else
{
int sum=0;
do
{
Should be
else
{
int sum=0;
count=0;
average=0.0f;
positive=0;
negative =0;
do
{

Categories

Resources