I am trying to get the average of user inputted numbers. Every time I input numbers the output is always-
The sum is 6
How many numbers: 4
Average: 2.0
A while loop is required, unfortunately for loops are not allowed. I am pretty new to Java so my formatting is sloppy. Where in my code are my problems?
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += count;
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
You have several errors here.
The main one that causes your error is sum += count. Instead of adding what the user has entered, you are adding the number that shows how many numbers there are. So it will always add 0+1+2+3 etc.
Another problem is that, once you change the above, you have to check whether the input == endingVariable before you add the input to the sum. So you have to write the if first, and then calculate the average inside it. Otherwise it will treat your -1 as part of the sequence of numbers to calculate.
You only need to add the input to the sum and increment the count if you find out that the input is not yet the same as endingVariable.
So:
Add the input, not the count, to the sum.
Calculate the average only when you have reached the final item.
Add the input to the sum and increment the counter only if your input is not endingVariable.
Try this one...
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += input; // you were doing mistake here.
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
Two big issues with your code. First, this line:
sum += count;
It's probably just a typo, but it should be obviously:
sum += input;
Second, once you fix that, you will notice you are including the -1 in your sum. You probably want something like this:
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
if (input == endingVariable) {
average = (double) sum / count;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
} else {
sum += input;
count++;
}
Thank you for explaining in detail. It works fine now, all I had to do was what you said is change the input, and move the sum += input and count after the final item in an else. I was having the hardest time trying to figure out why my -1 was being included
Related
I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.
I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;
I want my program that to accept user number input and output the sum from 1 up to the input number (using while loop).
Example: If input value is 4, the sum is 10 i.e., 1 + 2 + 3 + 4.
My code compiles but returns a never ending 1 until my jcreator stops responding.
import java.util.Scanner;
import java.io.*;
public class SumLoopWhile {
public static void main(String[] args) {
int number;
int sum = 1;
Scanner in = new Scanner (System.in);
System.out.println("Enter number: ");
number = in.nextInt();
while (sum <= 10) {
System.out.println("Sum is: " + sum);
number++;
}
}
}
You should be comparing the value to the number that was input, and adding to the sum. Finally, display the result after the loop. Something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int number = in.nextInt();
int sum = 0;
int v = 0;
while (v <= number) {
sum += v;
v++;
}
System.out.println("Sum is: " + sum);
}
Which will print Sum is: 10 when the input is 4 (as requested).
I guess that what you want it's to modify the sum inside your while loop. Do it like this:
while (sum <= 10) {
sum = sum + number;
number++;
}
}
System.out.println("Sum is: " + sum);
You have to put your System.out.println out of the loop because you want to print the total value, not each sum that it's calculated in each iteration.
Also, it should be nice that when you want to initialize some int that will be a "total" variable (like the result of a sum, rest or whatever), initialize it to zero.
int sum = 0;
Your output variable sum is having the same value throughout the program.it is not getting altered.the while loop becomes infinite loop
The Condition
(sum <= 10) never becomes true and the while loop will run for infinite times
import javax.swing.JOptionPane;
public class SumUsingWhileLoop {
public static void main(String[] args) {
String input;
input = JOptionPane.showInputDialog("Input the number:");
int number;
number = Integer.parseInt(input);
int sum = 0;
int i = 1;
while (i <= number) {
sum += i;
i++;
}
JOptionPane.showMessageDialog(null, "Sum = " + sum);
System.exit(0);
}
}
The System.out.println should not be placed inside the while loop, because it will get executed as many times as the loop.If you want to print the sum value only once, then the statement System.out.println must be placed outside the loop block.
Just use another variable for counting the iterations.For example
while(count<=number)
{
sum=sum+count;
count++
}
System.out.println("Sum is: "+ sum);
I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);
how would i add numbers together in the same manner as if i were to print them for example.
System.out.println(numbers);
numbers++;
this would print like so.
1
2
3
4
etc
how would i add them together as 1+2+3+4
here is my current code on this question.
this is the exercise i am working on for my MOOC at the University of Helsinki i live in the US so its hard to ask for help because of the 8 hour time difference.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Until What?:");
// the user inputs a number here
int blockExe = 1;
// the blockExe variable is supposed to store a count of how many times the
// block has been executed which i belive should be limited to the user input
int userIn = Integer.parseInt(reader.nextLine());
int sum = userIn + blockExe;
// i am supposed to add the number of block executions the user input
// each time adding 1 to the execution so 1+2+3
// then printing the sum of those numbers
while (blockExe <= userIn) {
blockExe += 1;
if (blockExe + userIn == sum) {
break;
}
}
System.out.println("Sum is:" +sum);
}
}
This code is ambiguous:
while (blockExe <= userIn) {
blockExe += 1;
if (blockExe + userIn == sum) {
break;
}
}
Perhaps you want this:
int sum=0;
for(blockExe = 1;blockExe <= userIn; blockExe ++) {
sum+=blockExe;
}
System.out.println("Sum is:" +sum);
That line doesn't make sense. I think the number you are trying to output should be blockExe but it isn't really clear what you are trying to do from you description. Try changing that line to:
System.out.println("Sum is:" blockExe);
and see if that gets you closer to your answer.