I am learning Java and am having a very simple problem.
How to print the final sum from a while loop?
if I enter integers 10 10 40
the output I get is
10
20
60
but am only trying to get the final 60.
This answer can also relate to printing the final anything in a while loop as I just can't seem to get this.
my sample code below...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
System.out.println("The Sum is: " + total);
}
}
Your main problem is that you have put the print statement inside the loop.
Also, in.hasNextDouble() doesn't make sense for input from the keyboard; it is useful when you are reading data from a file or a Scanner for some string. You can use an infinite loop (e.g. while(true){...}) and break it when there is no input from the user.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up, press Enter without any input to exit: ");
double total = 0;
while (true) {
String input = in.nextLine();
if (input.isBlank()) {
break;
}
total += Double.parseDouble(input);
}
System.out.println("The Sum is: " + total);
}
}
A sample run:
Enter a sequence of numbers to sum up, press Enter without any input to exit:
10
20
30
The Sum is: 60.0
A demo of a Scanner for a string:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner("10 20 30");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
}
Output:
The Sum is: 60.0
The problem lies in: System.out.println("The Sum is: " + total);
If you would like for only the final sum to be printed it needs to be outside of the while loop.
Please, print the total outside of the loop and it will work fine !
Code:
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
Related
I'm trying to use recursion to take the output of an Array. I've been able to create the input where the input takes the array data but no matter what I input, the array continuously returns 0.0. I did a test print of the array and it appears the data is going to the array so I'm not sure where I'm going wrong.
import java.util.Arrays;
import java.util.Scanner;
public class AverageGradeCourtney {
public static void main(String args[])
{
int i = 0;
int sum = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
double average = findAverage(newClassSize);
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
//System.out.println(average);
}
System.out.println("The average for the class is: " + average);
}
public static double findAverage(int array[])
{
if (array.length==0)
{
return 0;
}
return findAverageHelper(array,0,0);
}
public static double findAverageHelper(int[] array, int index, int sum)
{
if (index==array.length)
{
return (double) sum/array.length;
}
return findAverageHelper(array, index+1, sum+=array[index]);
}
}
The output continues to look like this:
Please enter the class size:
2
Please enter the grade of the user at: 1
12
Please enter the grade of the user at: 2
5
The average for the class is: 0.0
I have a small piece of code that continuously asks the user to input a number until it receives an input that is divisible by 10 (input % 10) and sums all inputs however it does not add the first input
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int input, sum = 0;
System.out.print("Enter a number: ");
input = in.nextInt();
while (input % 10 != 0) {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
if (input % 10 == 0) {
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
}
}
Example run
Enter a number: 15
Enter a number: 27
Enter a number: 45
Enter a number: 50
The total value is: 122
The last input was divisible by 10
The total value is 122 even though it should be 137 because it did not add the first input which is 15
You're tossing the first line away. This seems like a perfect opportunity to use a do-while instead.
Also, you can move the actual printing outside the loop.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
Note that this lays on the premise that you still want to add the last value to the sum even if it was divisible by 10.
If that's not what you want, you need to make the addition conditional as well.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
if (input % 10 != 0)
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. The user can enter any amount of numbers. When they enter a negative number, the program does the adding/averaging. When i enter a number into cmd line it only lets me enter one. Can anyone help me improve this?
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Statistics Program, assignment one, program
Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop,
enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
int amount = 0;
double totaladded = 0;
double userinput = 0;
userinput = keyboard.nextDouble();
while (userinput >= 0);
{
if(userinput > 0 )
{
totaladded = totaladded+userinput;
amount++;
}
}
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
}
use a do while loop instead,
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int amount = 0;
double totaladded = 0;
double userinput = 0;
do {
System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
userinput = keyboard.nextDouble();
if(userinput > 0 ) {
totaladded += userinput;
amount++;
}
} while (userinput >= 0);
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)
I have like 3 hours trying to solve this simple problem. Here is what I am trying to accomplished: Ask the user to enter a number, and then add those numbers. If the users enters five numbers, then I should add five numbers.
Any help will be appreciated.
import java.util.Scanner;
public class loopingnumbersusingwhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input;
System.out.println("How Many Numbers You Want To Enter");
total = kb.nextInt();
while(input <= kb.nextInt())
{
input++;
System.out.println("How Many Numbers You Want To Enter" + input);
int input = kb.nextInt();
}
}
}
Your current code is trying to use input for too many purposes: The current number entered, the amount of numbers of entered, and is also trying to use total as both the sum of all numbers entered and the amount of numbers to be entered.
You'll want 4 separate variables to track these 4 separate values: how many numbers the user will entered, how many they entered so far, the current number they entered, and the total.
int total = 0; // The sum of all the numbers
System.out.println("How Many Numbers You Want To Enter");
int count = kb.nextInt(); // The amount of numbers that will be entered
for(int entered = 0; entered < count; total++)
{
int input = kb.nextInt(); // the current number inputted
total += input; // add that number to the sum
}
System.out.println("Total: " + total); // print out the sum
Add this code after you take how many numbers the user wants to add:
int total;
for(int i = 0; i < input; i--)
{
System.out.println("Type number: " + i);
int input = kb.nextInt();
total += input;
}
To print this just say:
System.out.println(total);
import java.util.Scanner;
public class LoopingNumbersUsingWhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input=0;
int total = 0;
System.out.println("How Many Numbers You Want To Enter");
int totalNumberOfInputs = kb.nextInt();
while(input < totalNumberOfInputs)
{
input++;
total += kb.nextInt();
}
System.out.println("Total: " +total);
}
}
You seem to be asking how many numbers twice.
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter");
int howMany = kb.nextInt();
int total = 0;
for (int i=1; i<=howMany; i++) {
System.out.println("Enter a number:");
total += kb.nextInt();
}
System.out.println("And the grand total is "+total);
}
What you should pay attention to:
name classes in CamelCase starting with a big letter
initialize total
don't initialize input twice
show an appropriate operand input request to your user
take care of your loop condition
don't use one variable for different purposes
which variable should hold your result?
how to do the actual calculation
Possible solution:
import java.util.Scanner;
public class LoopingNumbersUsingWhile {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter: ");
int total = kb.nextInt();
int input = 0;
int sum = 0;
while (input < total) {
input++;
System.out.println("Enter " + input + ". Operand: ");
sum += kb.nextInt();
}
System.out.println("The sum is " + sum + ".");
}
}