简体   繁体   中英

How can I use a while loop in this code?

I am working through Learn Java The Hard Way and I am stuck on this study drill, which is to use a while loop to do the same thing as this code. I was wondering if you guys could help me out. Most of my attempts have resulted in an infinite while loop, which is what I do not want.

import java.util.Scanner; 

public class RunningTotal
{   
    public static void main( String[] args)
    {
        Scanner input = new Scanner(System.in);

        int current, total = 0;

        System.out.print("Type in a bunch of values and I'll ad them up. ");
        System.out.println( "I'll stop when you type a zero." );

        do
        {   
            System.out.print(" Value: ");
            current = input.nextInt();
            int newtotal = current + total;
            total = newtotal; 
            System.out.println("The total so far is: " + total);
        }while (current != 0);

        System.out.println( "Final total: " + total);

    }
}

A solution that doesn't change all that much code:

int current = -1;

while (current != 0) {
    System.out.print(" Value: ");
    current = input.nextInt();
    int newtotal = current + total;
    total = newtotal; 
    System.out.println("The total so far is: " + total);
}

I don't understand why are you processing(adding to total) when user has entered 0. I know it makes no difference but why unnecessary computations?

Also why define int newtotal in each loop. You can simply add the sum to the total.

So the while loop code will go something as follows

    while((current = input.nextInt()) != 0) {
       total = total + current;
        System.out.println("The total so far is: " + total);
    } 

Turning my comment into an answer:

One possible solution:

boolean flag = true;
while(flag)
{   
    System.out.print(" Value: ");
    current = input.nextInt();
    int newtotal = current + total;
    total = newtotal; 
    System.out.println("The total so far is: " + total);
    if(current == 0)
        flag = false;
}

Another possible solution:

while(true)
{
    System.out.print(" Value: ");
    current = input.nextInt();
    int newtotal = current + total;
    total = newtotal; 
    System.out.println("The total so far is: " + total);
    if(current == 0)
        break;
}

What about the next:

Scanner input = new Scanner(System.in);

System.out.print("Type in a bunch of values and I'll ad them up. ");
System.out.println( "I'll stop when you type a zero." );

int total = 0;
for (int current = -1; current != 0;) {
    System.out.print(" Value: ");
    current = input.nextInt();
    total += current; 
    System.out.println("The total so far is: " + total);
}

System.out.println( "Final total: " + total);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM