User
User

Reputation: 29

Asking User Multiple Times for Input in Java

So far I have this:

package CashRegister;

import java.util.Scanner;

public class CashRegister {

    public static void main(String[] args) {
        Scanner askPrice = new Scanner(System.in);  
            for(double i = 0 ; i < 3; i++);  
            {
                System.out.println("Enter a value") ;
                double price = askPrice.nextDouble();
            }
    }    
}

How can I prompt the user for three values and add them together?

Upvotes: 1

Views: 10401

Answers (2)

darijan
darijan

Reputation: 9775

Take a look at this example I built on your code:

double[] price= new double[3];
for (int i=0; i<3; i++) {
     System.out.println("Enter another ");
     double price[i] = askPrice.nextDouble();
} 

Later on, you can iterator over the price array, and add all the values:

double total = 0.0;
for (int i=0; i<price.length; i++) {
    total += price[i];
}

Upvotes: 1

stinepike
stinepike

Reputation: 54672

seems like a homework . So just a hint here. Try to learn and do by yourself with the help

To calculate the sum you need to declare a variable out of the for loop scope. so declare a variable say sum and after each input add price to sum. After the end of loop the sum will containt the result.

Edit:

we all missed a minor thing.. You placed a semicolon (;) after for loop remove this..

so use

for(double i = 0 ; i < 3; i++) 

instead of

for(double i = 0 ; i < 3; i++); 

As you have used semicolon the for loop has a blank statement. So your input is not in the scope of for loop.

Upvotes: 1

Related Questions