Java writing for loop with user input - java

/**I am trying to ask for user input for the number of the books they want to order, then using for find the cost of each book, total them up and give them their receipt at the end for their order. I understand how to give them the output just having trouble with my loop.*/
import java.util.Scanner;
public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal, subtotal, taxPaid;
System.out.print("Please enter the number of books you're ordering: ");
double numberOfBooks = in.nextDouble();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;
}
double subtotal = numberOfBooks * priceOfBooks;
double taxpaid = subtotal * (TAX);
double shippingCharge = SHIPPING * numberOfBooks;
double sumOfOrder = bookSubtotal + priceOfOrder + shippingCharge + TAX;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + subtotal);
System.out.println("Tax: $" + taxPaid);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}

You seem to increment counter twice:
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;//this line
}
What happens in this line is that you increment counter, but the loop does that for you, because of:
for(counter = 0;counter<numberOfBooks;counter++)
the counter++ in that line increments counter for you, so just remove the
counter++;
line in the for loop (the one I wrote this line next to)
Also, you should set a value to bookSubtotal:
int bookSubtotal = 0;
in the beginning.
Additionally, you might want to make numberOfBooks an integer:
int numberOfBooks = in.nextInt();
And you shouldn't re declare subtotal twice, just remove the word double in the line:
double subtotal = (double)numberOfBooks * priceOfBooks;
Nor do you need the create taxpaid before the loop, because you have taxPaid after it. Naming is case sensitive, meaning capital letters Are ImpOrtaNt...

public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal = 0;
System.out.print("Please enter the number of books you're ordering: ");
int numberOfBooks = in.nextInt();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal += priceOfBooks;
}
double shippingCharge = SHIPPING * numberOfBooks;
double tax = TAX * bookSubtotal;
double sumOfOrder = bookSubtotal + shippingCharge + tax;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + bookSubtotal);
System.out.println("Tax: $" + tax);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}

Related

Allow for a variable to affect number of statements in a loop

Is there any way to allow "testscore" variable to affect the number of statements in the do while loop? Like if say testscore = 4, I can have up to score4, and it will be included in the calculations.
import javax.swing.JOptionPane;
public class Task4 {
public static void main(String[] arges) {
double nof=1;
double testscore;
double score1;
double score2;
double score3;
double averagescore;
double x=11;
String input;
input=JOptionPane.showInputDialog("How many students do you have?");
nof = Double.parseDouble(input);
input=JOptionPane.showInputDialog("How many test scores per student?");
testscore=Double.parseDouble(input);
do {
input=JOptionPane.showInputDialog("Enter score 1");
score1= Double.parseDouble(input);
input=JOptionPane.showInputDialog("Enter score 2");
score2 = Double.parseDouble(input);
input=JOptionPane.showInputDialog("Enter score 3");
score3=Double.parseDouble(input);
averagescore = (score1 + score2 + score3)/testscore;
JOptionPane.showMessageDialog(null, "The student's average test score is " + averagescore);
x++;
} while (x <= nof);
}
}
Yes, you can use a for loop to gather the scores. If you're only using the scores to compute the average then you can just keep a running total. If you need the scores for more than that you can create a double[] scores = new double[testscores]; variable to store them in as they are read.
public static void main(String[] arges) {
int nof = 1; // this should be an int since you can't have a partial student
int testscore; // also an int since you can't have a partial test
String input;
input = JOptionPane.showInputDialog("How many students do you have?");
nof = Integer.parseInt(input);
input = JOptionPane.showInputDialog("How many test scores per student?");
testscore = Integer.parseInt(input);
for (int num = 1; num <= nof; num++) {
double total = 0;
for (int i = 0; i < testscore; i++) {
input = JOptionPane.showInputDialog("Student #" + num + ": Enter score " + i);
total += Double.parseDouble(input);
}
double averagescore = total / testscore;
JOptionPane.showMessageDialog(null, "Student " + num + "'s average test score is " + averagescore);
}
}

Problem with while loop and not getting the expected output?

This is a Java question and which I have a problem with the while loop. The program must allow the customer to enter the number of liters of petrol they wish to purchase and the liter value is $1.75. Then, for each
liter of petrol up to the quantity that the customer has entered, the program must display a
running total.
and this is the expected output and which I am not getting
Please Enter the Litres of Petrol (a whole number): 20
Litre 0: $0.0
Litre 1: $1.75
Litre 2: $3.5
...
Litre 19: $33.25
Litre 20: $35.0
and this is my code so far.
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
int numOfLiter;
System.out.println("Please enter the liters of Petrol: ");
numOfLiter = kb.nextInt();
double pricePerLitre = 1.75;
int count = 0;
while (count <= 10) {
Double total = pricePerLitre + count;
System.out.println("Liter " + count + ": " + total);
count++;
}
}
As per your output, your while loop should loop till the input provided i.e numOfLiter
int count = 0;
while (count <= numOfLiter) {
Double total = pricePerLitre * count;
System.out.println("Liter " + count + ": " + total);
count++;
}
And, also
Double total = pricePerLitre + count
should be
Double total = pricePerLitre * count
You can use a simple for-loop to achieve the same.
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
int numOfLiter;
System.out.println("Please enter the liters of Petrol: ");
numOfLiter = kb.nextInt();
double pricePerLitre = 1.75;
for (int i = 0; i <= numOfLiter; i++) {
Double total = pricePerLitre * i;
System.out.println("Liter " + i + ": " + total);
}
}
Try
Double total = pricePerLitre * count;
Instead of :
Double total = pricePerLitre + count;
In your code.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the liters of Petrol: ");
int numOfLiter = kb.nextInt();
double pricePerLitre = 1.75;
IntStream.range(0, numOfLiter + 1).forEach(i -> System.out.println("Liter " + i + ": " + i* pricePerLitre));
}
But in real code better use BigDecimal

How to output each stock?

I have to do this program where I have to display the calculation of the profit for each individual stock, but I also have to display the profit for the total amount of stocks. My code only has it so it displays the calculation for all of the stocks:
import java.util.Scanner;
public class KNW_MultipleStockSales
{
//This method will perform the calculations
public static double calculator(double numberShare, double purchasePrice,
double purchaseCommission, double salePrice,
double salesCommission)
{
double profit = (((numberShare * salePrice)-salesCommission) -
((numberShare * purchasePrice) + purchaseCommission));
return profit;
}
//This is where we ask the questions
public static void main(String[] args)
{
//Declare variables
Scanner scanner = new Scanner(System.in);
int stock;
double numberShare;
double purchasePrice;
double purchaseCommission;
double salePrice;
double saleCommission;
double profit;
double total = 0;
//Ask the questions
System.out.println("Enter the stocks you have: ");
stock = scanner.nextInt();
//For loop for the number stock they are in
for(int numberStocks=1; numberStocks<=stock; numberStocks++)
{
System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
numberShare = scanner.nextDouble();
System.out.println("Enter the purchase price" + numberStocks + ": ");
purchasePrice = scanner.nextDouble();
System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
purchaseCommission = scanner.nextDouble();
System.out.println("Enter the sale price:" + numberStocks + ": ");
salePrice = scanner.nextDouble();
System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
saleCommission = scanner.nextDouble();
profit = calculator(numberShare, purchasePrice, purchaseCommission,
salePrice, saleCommission);
total = total + profit;
}
//Return if the user made profit or loss
if(total<0)
{
System.out.printf("You made a loss of:$%.2f", total);
}
else if(total>0)
{
System.out.printf("You made a profit of:$%.2f", total);
}
else
{
System.out.println("You made no profit or loss.");
}
}
}
How can I get it so each individual stock profit gets shown, with the profit of all the stocks together?
Try maintaining a separate Map for profit/loss. You may want to accept Stock Name as an input which will help manage individual stocks effectively.
// Map of stock name and profit/loss
Map<String,Double> profitMap = new HashMap<String,Double>();
After calculating profit/loss, add entry to map
profitMap.put("stockName", profit);
total = total + profit;
At the end of your program, iterate and display profit/loss for each Stock from Map.
for (Entry<String, Integer> entry : profitMap.entrySet()) {
System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
}

Print result of a loop in Java

This code doesn't work. I get the following errors (in eclipse) that I can't seem to resolve:
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
Syntax error, insert ";" to complete BlockStatements
Duplicate local variable interest
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("input: ");
String input = in.next();
Integer interest = null; //to define interest
do
{
double interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
};
}
The variable interest is declared twice.
Here is a slightly cleaned up version of your code:
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("press 'N' to exit");
String input = in.next();
double interest = 0; //to define interest
do
{
interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
}
}

How would i program this correctly?

what the program wants me to code:
Code an executable program that will produce
an invoice for a customer ordering a number
of products at a store. A sample run of the
program is shown to the right.
Your program
must ask for the number of products (up to a
maximum of 12 products may be ordered) and
then successively ask for the product name and
its cost. The invoice produced includes:
 the title of the store (as shown),
 product names and their cost,
 calculated cost of all products,
 calculated 5% sales tax,
 overall total cost
 a thank you.
The products and their cost must be kept in
parallel arrays. Two methods must be coded.
One method will display the title. The second
method will accept the calculated cost of all
products and return the calculated sales tax.
The method that computes the sales tax must
use a named constant for the 5% tax rate.
picture of example run of what it should look like: http://imgur.com/F3XDjau
Currently my program is this so far, but im not sure if it is correct or if i need to make the variables into an array.
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int product;
String products;
double cost;
System.out.println("How many products? ");
product=input.nextInt();
for(int i = 0; i < product; i++){
System.out.println("Product Name: ");
products=input.next();
System.out.println("Cost: ");
cost=input.nextDouble();
}
}
}
this is how you can fill your array:
double[] costArray = new double[product];
for(int i = 0; i < product; i++){
costArray[i] = input.nextDouble();
}
You need to use an array for variables products and cost like this:
static final float TAXES = 0.05f;
public static void main(String[] args) {
double sum = 0.0;
double tax;
Scanner input = new Scanner(System.in);
int product;
String products[];
double cost[];
System.out.println("How many products? ");
product = input.nextInt();
products = new String[product];
cost = new double[product];
for (int i = 0; i < product; i++) {
System.out.println("Product Name: ");
products[i] = input.next();
System.out.println("Cost: ");
cost[i] = Double.parseDouble(input.next().trim().replace(',', '.'));
}
indentedText();
for (int i = 0; i < product; i++) {
System.out.printf(products[i] + '\t' + "%.2f %n", cost[i]);
sum = sum + cost[i];
}
tax = calculateTaxes(sum);
System.out.printf("Sub total:" + '\t' + "%.2f %n", sum);
System.out.printf("Sales tax:" + '\t' + "%.2f %n", tax);
System.out.printf("Total to be paid:" + '\t' + "%.2f %n %n", (sum + tax));
System.out.print('\t' + "Thank you!");
}
private static void indentedText() {
System.out.print('\t' + "The Company Store" + '\n' + '\n');
}
private static double calculateTaxes(double sum) {
return sum * TAXES;
}

Categories