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..
Related
Im trying to configure my code to tell the user to re enter a number, taking them back to the scanner if it falls outside of my specified range of 25
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0)
System.out.println("Positive numbers only");// if number entered is negative
else if (number > 25)
System.out.println("Number to large to print");
else if (number <= 1)// if number entered is 0 or 1
System.out.printf("The factorial of " + number+ " is equal to " + factorial);
else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and storing again in factorial variable
}
System.out.println("The factorial of " + number +" is equal to " + factorial);
}
To simplify the logic, you could extract it to the separate method. The logic itself is pretty strightforward:
in loop
ask a number
check if the number within the bounds
if not repeate or return if yes
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int num = getNumberWithin(scan, 1, 25);
}
private static int getNumberWithin(Scanner scan, int lo, int hi) {
while (true) {
System.out.format("Enter a number between %d and %d: ", lo, hi);
int num = scan.nextInt();
if (num >= lo && num <= hi)
return num;
System.err.format("The number should be between %d and %d\n", lo, hi);
System.out.println();
}
}
boolean correctInputn = false;
while(!correctInputn)
{
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0) {
System.out.println("Positive numbers only"); // if number entered is negative
correctInputn = false;
continue; // if user enters number less than 0 loops back to code start
} else if (number > 25) {
System.out.println("Number to large to print");
correctInputn = false;
continue; // if user enters number over 25 loops back to code start
} else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial * mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and stored again in factorial variable
}
System.out.println("The factorial of " + number +" is equal to " + factorial);
break;
}
}
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;
So, I have already figured out how to calculate the average and number of integers entered; however, I cannot seem to figure out how to figure out the largest, smallest, even and odd numbers. I have tried several things, but it does not work.
Any tips or suggestions? I do not need for you to write anything for me, but a little guidance would be appreciated. (this is for school, do not want to cheat, just need some help).
import java.util.Scanner;
public class Lab4
{
public static void main(String[] args)
{
double large = Integer.MAX_VALUE;
double small = Integer.MIN_VALUE;
double evenCount = 0;
double oddCount = 0;
double foot = 0;
double ball = 0;
double eagles = 0;
System.out.println("Enter positive or negative integers -- enter zero to quit");
Scanner scan = new Scanner(System.in);
boolean philly = false;
while (!philly)
{
eagles = scan.nextDouble();
if (eagles == 0)
{
philly = true;
}
else
{
foot = foot + eagles;
ball++;
}
}
if (eagles%2==0)
{
evenCount++;
System.out.println("The number of even integers is: " + evenCount);
if (eagles%2==1)
oddCount++;
System.out.println("The number of odd integers is: " + oddCount);
if (eagles < small)
small = eagles;
System.out.println("The smallest integer entered is: " + small);
if (eagles > large)
large = eagles;
System.out.println("The largest integer entered is: " + large);
if (ball > 0)
System.out.println("The number of integers entered is: " + ball);
double avg = foot / ball;
System.out.println("Average of integers: " + avg);
}
else
{
System.out.println("No data");
}
}
}
Some tips:
1)
Make all variables of type Integer. You cannot determine odd/even from Double values.
2)
Initialize the large with Integer.MIN_VALUE and small with Integer.MAX_VALUE.
3)
The check for odd/even/smaller/greater should be executed within the while loop.
Ok, so I am working on a java program for my college class and I have now spent many hours trying to figure out what I am doing wrong.
My program is below. What it needs to do is convert an integer into single digits and then add them all up. It has to display the original number, the individual digits and then the sum.
Part of the project is it has to accept negative digits and then display the positive numbers and the sum, however with my array it is displaying a -1 as the first number when a negative number is input and I CANNOT for the life of me figure out how to fix it.
Example: input of -3456 ends up displaying -1, 3, 4, 5, 6 and a sum of 17 which is obviously wrong.
Any help would be immensely appreciated, thanks!
import java.util.*;
import javax.swing.JOptionPane; //import package for using dialog boxes
import java.util.Arrays; //import package for arrays
public class Project4
{
public static void main(String args[])
{
//declares and initialize variables sum & counter
int sum = 0;
int counter = 1;
//asks for integer input and stores as a string in numInput
String numInput = JOptionPane.showInputDialog(null, "Enter an integer: ", "User Input", JOptionPane.QUESTION_MESSAGE);
int input = Integer.parseInt(numInput);//parses the value of numInput as an integer and stores as input
int numLength = String.valueOf(input).length();//sets numLength as the length of input
int [] varArray = new int[numLength];//initilizes an array to match numLength
if(input == (-input))//tests for negative input value
{
input = (input * (-1));//corrects the negative input value
for (int i = 0; i < numLength; i++ ) //starts a for loop
{
String var = numInput.substring(i,counter);//stores the value of the number at the location between i and counter as var
int numVal = Character.getNumericValue(var.charAt(0));//sets numVal to the numeric value of the character at 0
varArray[i] = numVal;//saves the numVal to the array at position i
sum = sum + numVal;//adds the sum of the numbers as the loop goes
counter++;//increments the counter
}
}
else //starts alternate loop if input was not a negative value
{
for (int i = 0; i < numLength; i++ )
{
String var = numInput.substring(i,counter);
int numVal = Character.getNumericValue(var.charAt(0));
varArray[i] = numVal;
sum = sum + numVal;
counter++;
}
}
JOptionPane.showMessageDialog(null, "The Digits of Integer Entered " + input + " are: " + Arrays.toString(varArray).replace("[", "").replace("]", "") + "\nThe sum is: " + sum, "NUMBERS", JOptionPane.INFORMATION_MESSAGE);
System.exit(0); //exits program and is required when using GUI
}
}
if(input == (-input))
doesn't test for negative inputs, it tests if the input is 0.
if(input < 0)
tests for negative input.
Always avoid an if.
input = Math.abs( input );
This takes care of the sign and doesn't need an if.
While I'm at it, this is the preferred way to compute the digit sum (provided you don't need to store the digits in an array, from left to right):
int sum = 0;
while( input > 0 ){
sum += input%10;
input /= 10;
}
Replace Condition
if(input == (-input))
By
if(Math.signum(input) == -1.0)
Or
if(input < 0)
try {
int integerNumber = Integer.parseInt(input);//It may positive or negative
if(integerNumber > 0) {
//Do the stuff positive number
} else if(integerNumber < 0){
integerNumber = (integerNumber * -1);
//Do the stuff for negative number
} else {
System.out.println("Enter Number is zero ::");
}
}catch(NumberFormatException nfe) {
System.out.println("Please Enter a Integer Number :::"+input);
}
//I think this code will help for you.
I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.
Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum;
sum = 0;
double average;
Scanner input = new Scanner(System.in);
int count; count = 0;
average = 0;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
System.out.println("Average = " + average);
}
}
This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this
while (integer != 0) {
count += 1;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
Explanation
First of all, when you define data types, you can set their default value in the definition. Ex:
double sum = 0;
vs
double sum;
sum = 0;
Secondly, sum = sum + integer; is the same as: sum += integer;
Thirdly, count = count + 1; is the same as: count += 1 OR (and better yet), count++;
As for your actual algorithm, there is one problem and one suggestion:
you are not changing integer's value after each loop. So, you can
either do that in the while condition: while ((integer =
input.nextInt()) != 0) { or, at the end of each loop:
while (integer != 0) {
count ++;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
This is a suggestion for technically better code (in my opinion), but it looks better, is more intuitive and requires less calculations to calculate the average after the while loop is done instead of during. That way, you only calculate it once, where needed, vs. every loop, which is not needed.
________________________________________________________________________________
The Code (complete class)
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Please enter an integer: ");
// set integer = to the nextInt() while looping so it calculates properly
while ((integer = input.nextInt()) != 0) {
count ++;
sum += integer;
}
average = sum / count; // calculate the average after the while-loop
System.out.println("Average = " + average);
}
}
________________________________________________________________________________
Example input/output:
Please enter an integer:
5
10
15
0
Average = 10.0
So it did 5 + 10 + 15 = 30 (which is the sum), and then the average is 30 / 3 (30 is the sum, 3 is the count), and that gave you Average = 10.0.
You need to move integer = input.nextInt(); inside the loop, so your program will collect inputs in a loop. See the corrected version:
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer = 0, count = 0;
double sum = 0.0, average = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
System.out.println("Average = " + average);
}
}
The problem is that the input.nextInt() should be part of the loop. The way you wrote it, the code gooes into an infinite loop whenever the first input is non-zero. Instead, do:
while ((integer = input.nextInt()) != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
In the loop:
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
This will only stops when integer is 0, but this variable is not changing in the loop, so it will never be 0 if it wasn't already in the first place.
According to what you said you want to do, you should probably repeat the call to integer = input.nextInt(); inside your loop, lke this:
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
Also, as others have said, you only need to compute the average once after the loop, so I moved it too.