1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, but how can I repeat the step to ask the user for an input three times?
you have already done that.. after showing enter value when user will enter the number and press enter the next prompt will show !!!
But it doesn't! For example, when I run that code, it asks me to enter a value. Once I enter, let's say "3", it prints "3.0". I need to make it where it keeps asking me for a value two more times. That's what I am asking. Thanks!
gotcha.. check my answer @User
1

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];
}

2 Comments

add try-catch to double price[i] = askPrice.nextDouble(); } ;
you don't need 2 for-loops to calculate sum, you can optimize the code with single for-loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.