0

Currently I am just starting out with java and need some help with the basics. I would like to make the program to be universal and for the user to input the price of the books, instead of it being written in the code. I have looked up and tried on my own but I just keep falling over and over again so if you anyone could explain it in lame terms it would be appreciated.

package com.test1;
public class example1 
{
    public static void printTotalAmountForBooks(double[] prices) 
    {
        double totalAmount = 0;

        for (double singleBookPrice : prices) 
        {
            totalAmount += singleBookPrice;
        }
        System.out.println("The total amount of all books is: " + totalAmount);
    }

    public static void main(String[] args)  
    {
        double [] pricesArr;
        pricesArr = new double[] { 15.93, 12.45, 22.54, 14.56, 23.21 };
        printTotalAmountForBooks(pricesArr);
    }
}
Ronald
  • 2,842
  • 16
  • 16
Dari Popov
  • 13
  • 3
  • 6
    Does this answer your question? [How to get the user input in Java?](https://stackoverflow.com/questions/5287538/how-to-get-the-user-input-in-java) – OH GOD SPIDERS Nov 08 '21 at 10:34

1 Answers1

0

You are going to need to make a scanner. Let's say I am figuring out how much money I made from selling tickets. I want to input the price of a ticket, and how many tickets I sold. First, you make a scanner object like this.

Scanner sc = new Scanner(System.in);

This makes a new scanner object that reads what you type in the console. Now, we can call the .nextDouble() method on the scanner we made. Note that you can name your scanner anything, it doesn't need to be sc.

Now we call this method and save it to a variable, like this:

double pricePerTicket = sc.nextDouble();

With that line, the code is going to wait until you type in a double into the console. If you type something that is not a number, it will crash your program.

We can then ask for the amount of tickets, the same way, like this:

int ticketsSold = sc.nextInt();

This does nearly the same thing as before, but with an integer. Typing in something that is not an integer will crash. Now, you can multiply the two. You can put a print statement before like this:

System.out.println("How many tickets did you sell today?");
int ticketsSold = sc.nextInt();
System.out.println("How much does a ticket cost?");
double pricePerTicket = sc.nextDouble();
double moneyMade = pricePerTicket * ticketsSold;
System.out.println("Dang! You made " + moneyMade + " dollars today!");

It looks like you wanted each price to be different, though. What you can do is use a while loop to first ask for the price of the book. Then it asks if you want to continue (use sc.nextBoolean). Then, put that value in the while loop (). More information is here. Hope this helps a bit.

CiY3
  • 134
  • 10