Incorrect Largest Input - 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.
Also, as I input quit, I get for my largest number 214XXXXXXXX
Example of my output will be pasted at the end.
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);
Result:
Enter a sequence of integers. Any non-integer to quit
9 //input 1
odd: 1
sum 9
count 1
average 9.0
3 //input 2
odd: 2
sum 12
count 2
average 6.0
7 //input 3
odd: 3
sum 19
count 3
average 6.333333333333333
1 //input 4
odd: 4
sum 20
count 4
average 5.0
q //input 5: QUIT
smallest: 1
largest: 7 //This should be 9
even: 0
odd: 4
average: 5.0
Result 2:
Enter a sequence of integers. Any non-integer to quit
q //quit
smallest: 2147483647 //This should be 0
largest: 0
even: 0
odd: 0
average: 0.0
Any help would be appreciated. Thank you!

Take out else before checking if getInt is greater than max. You need to check for both the conditions, so don't put else there.

if (getInt < min) {
min = getInt;
} else if (getInt > max) {
max = getInt;
}
Change above code as mentioned below . You have to check both condition so change else if to if.
In if - else if
once a condition is satisfied, the appropriate statements are executed
and the remaining conditions are not evaluated.
if (getInt < min) {
min = getInt;
}
if (getInt > max) {
max = getInt;
}

First
9 wasn't assigned to max. Since 9 < min, The code evaluates min = getInt; and skip the else if part.
It should be :
if (getInt < min)
{
min = getInt;
}
if (getInt > max)
{
max = getInt;
}
Because a number can be both min and max.
Second
smallest: 2147483647 //This should be 0
This happen because you type in a character but scan in as an integer by usinggetInt = scan.nextInt(); (as well as store the input as an int).
You can fix this scan in the input as String first. Then, you determine if the input is an int or not by creating a method to check it. :
public static boolean isInteger(String s)
{
try
{
Integer.parseInt(s);
}
catch(NumberFormatException e)
{
return false;
}
// only got here if we didn't return false
return true;
}
Then, check if the input is an integer before you do the calculation.

As to your other problem, you have to initialize min as 0.
After that, check if the input is your first, and if so set min as that.
boolean isFirst = true;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if(isFirst)
{
min = getInt;
isFirst=false;
}
//Rest of your code
}

Related

How to display the min and max elements of an array?

I've been trying to solve this problem for quite some time now. I'm trying to display the min and max elements of an array, but the min always remains at 0. Here's the code that explains my issue:
public class ArrExs {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter the array capacity (min 1, max 20): ");
int n = input.nextInt();
while(n <= 0 || n > 20) {
System.out.print("enter a valid number and try again: ");
n = input.nextInt();
}
int[] nums = new int[n];
maxAndMin(nums);
}
public static void maxAndMin(int[] numbers) {
Scanner input = new Scanner(System.in);
System.out.println("enter your array elements: ");
int min = numbers[0];
int max = numbers[0];
for(int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
max = (numbers[i] > max) ? numbers[i] : max;
min = (numbers[i] < min) ? numbers[i] : min;
}
System.out.print("min = " + min + ", max = " + max);
}
}
The output:
enter the array capacity (min 1, max 20): 3
enter your array elements:
2
3
4
min = 0, max = 4
The min always remains at 0, I've tried to edit the code multiple times but I get the same result.
I've encountered this problem before and watched a video where the instructor's logic is to set the "Min" and "Max" to the first number entered by the user. Then there comes the relational operator to decide which is minimum and maximum.
The problem is on the line where you do int min = numbers[0]; because numbers is an empty array (all of the values are 0). Since min starts at 0 and nothing in the array is less than 0 then min will remain 0 forever.
Try making min start as a high value such as int.MaxValue and see if that fixes your problem.

control statement throwing arithmetic exception

this was supposed to be fairly simple, but apparently somethings wrong with my control boolean, when I input a negative number instead of ending the loop it throws an exception, any help is appreciated.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double average;
int count = 0, sum = 0, next;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
boolean areMore = true;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a negative number");
// not sure why i used a do while loop but it works i guess
do {
next = keyboard.nextInt();
sum = sum + next;
next++;
if (next < 0)
areMore = false;
} while (areMore == true);
{
sum = sum + next;
average = sum / count;
{// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
}
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
}
Error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.task.AverageMinMax.main(AverageMinMax.java:29)
Your issues:
You increase next instead of count.
Outsider (sum = sum + next) is also wrong. You should not add next after loop breaks.
Min-max should be calculated inside the loop.
Some improvement suggestions:
Use while it is cleaner than do-while.
Use hasNextInt to check if it is a number or not.
If your input is a char or any special character while loop breaks.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double sum = 0, average =0;
int count = 0, next = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a char or any special character to calculate and exit");
// use while it is more cleaner.
// use hasNextInt to check if it is number or not
// if your input is a char or any special character while loop breaks
while (keyboard.hasNextInt()) {
next = keyboard.nextInt();
sum = sum + next;
// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
count++;
}
average = sum / count;
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Issues
count is not incremented and its causes divide by 0 error
computation of max, min, sum, average seems incorrect
solution
Repeated read input(integer) from user
if the input is positive, add to sum, update min, update max and update count
if its negative, break the input loop
if any input is passed, then compute average
if no input is passed, then do not compute average
import java.util.Scanner;
class AverageMinMax {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
int count = 0, sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
System.out.println("Please enter the numbers you wish to evaluate.");
System.out.println("Followed by a negative number to stop input");
do {
final int next = keyboard.nextInt();
if (next < 0) {
break;
}
sum = sum + next;
max = Math.max(max, next);
min = Math.min(min, next);
count++;
} while (true);
if (count > 0) {
double average = (sum * 1.0) / count; // need to multiply by 1.0 to have fraction
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
} else {
System.out.print("No input to process");
}
}
}
You are getting ArithmeticException because you initialize count to 0. But after that when you are getting input from console. instead of increasing the count and doing count++. You are doing next++ in the loop.
And also getting the min max should also needs to be done in loop currently they are just in block. Although they are not responsible for your error of divide by zero.
this line is
average = sum / count;

How to Pass This Test Case?

I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.

My if statements will not take new values

The object is to get the average of the entered values.
It is to stop when a negative number is entered.
I am trying to get the smallest and largest values entered.
The problem I am having is that my if statements will not take the smallest/largest new values entered.
It just gives me the Integer.Max_Value and Integer.Min_Value.
import java.util.Scanner;
public class LargeSmallAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
double count = 0;
double amtOfNums = 0;
int input = 0;
int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE;
int number;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
while(input>=0){
for(int counter=1; counter<amtOfNums; counter++){
number=scan.nextInt();
if(number<smallest)
smallest=number;
if(number>largest)
largest=number;
}
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
}
}
Currently you have two loops. One sums the numbers, and the other finds the largest and smallest numbers. Given your output, it sounds like you should be doing it all in one loop - ideally with more useful variable names too. (Your count is actually a sum, not a count... and there's no need for it to be a double. You could make it a long if you really want to avoid overflow. Yes, you need to perform floating point arithmetic for your average, but you can do that when you take the average... your sum is logically an integer.)
int sum = 0;
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
int count = 0;
while ((input = scan.nextInt()) >= 0) {
count++;
sum += input;
// Alternative: smallest = Math.min(smallest, input)
if (input < smallest) {
smallest = input;
}
// Alternative: largest = Math.max(smallest, input)
if (input > largest) {
largest = input;
}
}
// Cast for count is just to force floating point division.
System.out.println("You entered " + count +
" numbers averaging " + (sum / (double) count) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
There is a problem with your while loop condition: while(input>=0){
here input will be always less than zero due to your previous while statement:while ((input = scan.nextInt()) > 0)
Here while loop exits only when you enter a number which is less than zero.. so input will have that value..

what is wrong with my method for avg? [duplicate]

This question already has answers here:
How do I get this code to stop input when the sum exceeds 100 and still preform the sum and average?
(2 answers)
Closed 9 years ago.
Yes, I know there are a lot of methods here. It's part of the assignment. In this code everything works as intended except that when numbers are entered that equal sum<=100, the "average" output is wrong. For example: if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25.... the average should be 12.3333. Now, if i enter in 8, 10, 99 the output is count 3 sum 117 and average 39 which is correct. Why is it working for sum>100 but not sum<=100??? I don't get it. What am I missing?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the sentinel value
* of 0 that the user had to enter to exit the input loop in the overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ", Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
}
}
The reason is that you're exiting the while loop in different ways depending on the total sum. If the sum is less than 100, even when you enter the number 0 to "exit", you're still going through the loop an extra time. To be honest, the entire loop needs to be completely restructured; a do...while loop would be much easier to read and debug.
The issue is because of the way you exit the while loop as mentioned by #chrylis. So in case where the sum is <= 100 the counter is 1 larger. But when you print it you get correct result because you update the counter value here:
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
As you see in your example:
"if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25"
it is because the counter value is 4 (so the avg will be 37/4 = 9.25), but while displaying the result you subtract counter by 1, therefore you get the count as 3.
The do-while loop will solve the issue as the condition would be checked at the last thus the loop will exit in same manner for both <=100 and '>100`.
The do-while loop would be like this:
do{
//here goes your code
}while (input != 0);
Your counter is 1 larger than necessary. Dividing by (counter - 1) would fix it.

Categories