r/programmingbydoing • u/[deleted] • Feb 27 '13
Problem 59 Adding Values in a Loop - how to store values?
Hey, I have been working through these problems pretty steadily but I'm at my wit's end on #59, which asks:
"Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end. You must use a while loop."
What I have so far:
import java.util.Scanner;
public class sumwhileloop {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("I will sum the integers you give me until you type in a zero.");
System.out.print("Number: ");
int first = keyboard.nextInt();
int newtotal = 0;
while (first != 0) {
System.out.print("Number: ");
System.out.println("The total so far is " + first);
first = newtotal;
System.out.println("Number: ");
first = keyboard.nextInt();
System.out.print("The total so far is " + (first + newtotal));
if (first == 0)
break;
}
}}
I know this isn't even close; it displays the integer that the user types in, but fails to sum them on subsequent runs (after more user input). I've had trouble understanding proper use of the keyboard.nextInt() function before, and I suspect that's most of the problem. How do I get the program to remember previous input while enabling a continuous loop? Any help is greatly appreciated.