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
Related
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);
}
}
Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}
/**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 + ".");
}
}
I want to get all the input values from entered Sales amount but it only gives me the last value I input , and also to display all amount . thanks
This is the ouput looks like.
Please enter the number of salespeople to be processed: 3
Enter and ID number and Sales Amount seperated by a space: 1 150
Enter and ID number and Sales Amount seperated by a space: 2 250
Enter and ID number and Sales Amount seperated by a space: 3 350
Weekly Sales by Salesperson 0 1 2 .
the 3 amount of sales should be displayed here.
Total Sales: 1800
{
int i = 0;
System.out.print("Please enter the number of salespeople to be processed: ");
howmany = input.nextInt();
int[] array = new int[howmany];
while ( i <= array.length - 1 )
{
System.out.print("Enter and ID number and Sales Amount seperated by a space: ");
numberOfSales = input.nextInt();
Salesmoney = input.nextInt();
addwan += Salesmoney;
i++;
}
HAHA();
for (int j = 0; j < i ; j++)
{
System.out.print( + j + " ");
addwan += Salesmoney;
System.out.print(Salesmoney + " ");
}
System.out.println("\nTotal Sales: " + addwan + " ");
}
public static void HAHA()
{
System.out.println("\n\t\t\t\tWeekly Sales by Salesperson");
}
}
roughly scetched, I guess you would want to have smthg like this:
System.out.print("Please enter the number of salespeople to be processed: ");
howmany = input.nextInt();
int[][] array = new int[2][howmany];//2D array to store the amount, and worth of the item
for (int i=0; i<howmany;i++ )
{
System.out.print("Enter and ID number and Sales Amount seperated by a space: ");
array[0][i] = input.nextInt();
array[1][i] = input.nextInt();
}
System.out.println("\n\t\t\t\tWeekly Sales by Salesperson");
int addwan=0;
for (int j = 0; j < howmany ; j++)
{
System.out.println( "Eintrag: "+j+" number of sales: "+array[0][j]+" itemworth: "+array[1][j]);
addwan+=array[0][j]*array[1][j];
}
System.out.println("\nTotal Sales: " + addwan + " ");
Guessed i right that your ID-number has to be multiplied with the amount? because i coundt figure out the 1800 sales... even thou they are 1700...
import java.util.Scanner;
public class Exchange {
public static void main(String[] args){
int howmany;
int totalAmount;
int[] arrayForId;
int[] arrayForSales;
Scanner inputData = new Scanner(System.in);
totalAmount = 0;
System.out.print("Please enter the number of salespeople to be processed: ");
howmany = inputData.nextInt();
arrayForId = new int[howmany];
arrayForSales = new int[howmany];
for(int i = 0; i < arrayForId.length; i++){
System.out.print("Enter an ID number and Sales Amount seperated by a space: ");
arrayForId[i] = inputData.nextInt();
arrayForSales[i] = inputData.nextInt();
}
System.out.println("\n\t\t\t\tWeekly Sales by Salesperson");
for (int i = 0; i < arrayForId.length ; i++){
System.out.println("Id: " + arrayForId[i] + "\t Amount: " + arrayForSales[i]);
totalAmount += arrayForSales[i];
}
System.out.println("\nTotal Sales: " + totalAmount);
inputData.close();
}
}
hope this will help you.
I am new to stackoverflow. First I would like the program to loop with a price, then a question(enter another price?), price, then a question and so on. Below is the output.
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Please enter a price:
99
Please enter a price:
22
However it will keep looping at the end with "Please enter a price:". I want it to do:
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Enter another price?
y
Please enter a price:
22
Can anyone help me with this? Also, sometimes the average does not update fully. Thanks :)
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice;
System.out.println("Please enter a price: ");
integer = input.nextInt();
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
}
while (addPrice.equalsIgnoreCase("Y"));
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
You need to replace your while with an if
if (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
In fact, addPrice is not modified within your second while loop, and so you have an infinite loop.
In order to do the averaged price, you're in the right way but not in the right place :P
count = count +1 and sum = sum + integer should be done after each integer = input.nextInt(). In your current code, you don't increment the counter and don't add the integer for the last input.
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
}
}
while (addPrice.equalsIgnoreCase("Y"));
Finally here is a improved version which avoid the use of if.
int sum = 0;
int integer = 0;
String addPrice = "Y";
while( "Y".equalsIgnoreCase(addPrice) ) {
System.out.println("Please enter a price: ");
integer = input.next();
sum += integer ;
count++;
System.out.println("Enter another price? ");
addPrice = input.next();
}
int avg = sum / count ;
What you should do is change your logic a bit. You need to repeat two actions, entering a price and asking if the user wants to enter another price. Only one loop is required for this.
do {
System.out.println("Please enter a price: ");
integer = input.nextInt();
count = count + 1;
sum = sum + integer;
System.out.println("Enter another price? ");
addPrice = input.next();
} while (addPrice.equalsIgnoreCase("Y"));
i think you want something like this:
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice = "Y";
while (addPrice.equalsIgnoreCase("Y")){
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++;
sum += integer;
System.out.println("Enter another price? ");
addPrice = input.next();
}
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
Try this:
EDIT Added min and max.
public class ReadInPrice {
public static void main(String[] args) {
//better to use 2 scanners when dealing with both string and int
//one for string ; one for ints
Scanner strScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
boolean enter = true;
int sum = 0;
int count = 0;
int min=Integer.MAX_VALUE;
int max=0;
while (enter) { //while user wants to keep adding numbers
System.out.println("Please enter a price: ");
int price = intScanner.nextInt();
if(price < min)
min=price;
if(price > max)
max=price;
sum += price;
count++;
System.out.println("Enter another price? ");
String answer = strScanner.nextLine();
if (!answer.equalsIgnoreCase("Y"))
enter = false; //user doesn't want to keep adding numbers - exit while loop
}
double average = (double)sum / count;
System.out.println("Average = " + average);
System.out.println("Min = " + min);
System.out.println("Max = " + max);
strScanner.close();
intScanner.close();
System.exit(0);
}
}