Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to find out how much of the total amount variable 1 is responsible for and how much of the total cost variable 2 is responsible for. I have attached an image of my source code so far
the assignment instructions are: The program will then calculate the total of all the expenses, what each person should pay if the costs were divided equally, and how much each friend actually paid. If one person paid less than the other, then they will owe their friend some money.
import java.util.Scanner;
public class Trip {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double flight, hotel, meals, tour, total, owes;
String name1, name2;
double Lisa, Bart;
double input1, input2, input3, input4;
Lisa = 1;
Bart = 2;
System.out.print("Enter the first name: ");
name1 = keyboard.nextLine();
System.out.print("Enter the second name: ");
name2 = keyboard.nextLine();
System.out.print("Enter cost of flights: ");
flight = keyboard.nextDouble();
System.out.print("Who paid for the flights: Enter 1 for Lisa or 2 for Bart ");
input1 = keyboard.nextInt();
System.out.print("Enter cost of hotel: ");
hotel = keyboard.nextDouble();
System.out.print("Who paid for the hotel: Enter 1 for Lisa or 2 for Bart ");
input2 = keyboard.nextInt();
System.out.print("Enter cost of tour: ");
tour = keyboard.nextDouble();
System.out.print("Who paid for the tour: Enter 1 for Lisa or 2 for Bart ");
input3 = keyboard.nextInt();
System.out.print("Enter cost of meals: ");
meals = keyboard.nextDouble();
System.out.print("Who paid for the meals: Enter 1 for Lisa or 2 for Bart ");
input4 = keyboard.nextInt();
total = flight + hotel + meals + tour;
System.out.printf("Total bill for trip: %.2f \n", total);
owes = total / 2;
System.out.printf("Each person owes: %.2f", owes);
}
}
Say you have two people Max and Simon. You could do something like below where you first find the amount owed by Max using your logic. And then to find the amount owed by Simon you just use totalCost - amountMaxOwes:
import java.util.Scanner;
class Trip {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first name:");
String nameOne = scanner.nextLine();
System.out.print("Enter the second name:");
String nameTwo = scanner.nextLine();
System.out.print("Enter cost of flights:");
double flightsCost = scanner.nextDouble();
System.out.printf("Who paid for the flights? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidFlights = scanner.nextInt();
System.out.print("Enter cost of hotel:");
double hotelCost = scanner.nextDouble();
System.out.printf("Who paid for the hotel? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidHotel = scanner.nextInt();
System.out.print("Enter cost of tour:");
double tourCost = scanner.nextDouble();
System.out.printf("Who paid for the tour? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidTour = scanner.nextInt();
System.out.print("Enter cost of meals:");
double mealsCost = scanner.nextDouble();
System.out.printf("Who paid for the meals? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidMeals = scanner.nextInt();
double totalCost = flightsCost + hotelCost + tourCost + mealsCost;
System.out.printf("Total bill for trip: %.2f \n", totalCost);
// This stuff can be moved to a more appropriate place if you want to
double personOnePaid = 0;
if(whoPaidFlights == 1) personOnePaid += flightsCost;
if(whoPaidHotel == 1) personOnePaid += hotelCost;
if(whoPaidTour == 1) personOnePaid += tourCost;
if(whoPaidMeals == 1) personOnePaid += mealsCost;
double personTwoPaid = totalCost - personOnePaid;
System.out.printf("%s owes: %.2f \n", nameOne, personOnePaid);
System.out.printf("%s owes: %.2f \n", nameTwo, personTwoPaid);
}
}
Example Usage:
Enter the first name: Max
Enter the second name: Simon
Enter cost of flights: 299.34
Who paid for the flights? Enter 1 for Max or 2 for Simon: 1
Enter cost of hotel: 300.40
Who paid for the hotel? Enter 1 for Max or 2 for Simon: 2
Enter cost of tour: 55.00
Who paid for the tour? Enter 1 for Max or 2 for Simon: 1
Enter cost of meals: 314.15
Who paid for the meals? Enter 1 for Max or 2 for Simon: 1
Total bill for trip: 968.89
Max owes: 668.49
Simon owes: 300.40
Related
I am creating a program that takes in employee payroll information and then displays the average and total afterwards. Everything seems to be working correctly except for the fact I cannot get the program to end when I enter the sentinel value of -1 for the hours worked so that the program can display the total and average of the employees. Any help is greatly appreciated.
import java.util.Scanner;
public class PayrollDo
{
public static void main(String[] args)
{
int hoursWorked = 0;
int grossPay = 0;
int empCounter = 0;
int total = 0;
Scanner keyboard = new Scanner(System.in);
do {
total = total + grossPay; // add gross to total
empCounter = empCounter + 1; // incriment counter
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
//System.out.println("Grosspay is " + (hourlyWage * hoursWorked));
keyboard.nextLine();
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
} while(hoursWorked != -1);
// if user entered at least one employee
if (empCounter != 0) {
// use number with decimal point to calculate average of employees
int average = (int) total / empCounter;
// display total and average (with two digits of precision)
System.out.printf("%nTotal of the %d employees entered is %d%n",
empCounter, total);
System.out.printf("Employee average is " + average);
}
else {
// no employees were entered, so output appropriate message
System.out.println("No employees were entered");
}
}
}
Test soon after entering the value whether it is -1 or not
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
if (hoursWorked == -1) break;
edit
I think you will also have trouble with Integer division http://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0
You could restructure your do loop to put the hoursWorked input last (otherwise you have to complete the entries) - and also, add a conditional to reject all entries that cycle, otherwise empCounter is off by one. And I think the total calculation needs reworking too:
do {
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
keyboard.nextLine();
if (hoursWorked != -1) {
total = total + (hourlyWage * hoursWorked); //
empCounter = empCounter + 1; // incriment counter
}
} while(hoursWorked != -1);
In cases like this it can be simpler to have a question like "More Employees? (y/n)" that is used to terminate the loop, using a boolean flag as the while terminator.
My first assignment is to develop a code that allows the user to input data for the distance in miles they wish to travel, the fuel efficiency, and the cost of gas. Then create a code in order to calculate the total cost of the trip.
I have all the code for all the input values but I'm having trouble with the equation itself. Java is not recognizing "/". I can't understand what I'm doing unless I need to add a bit more code for the equation to work.
import java.util.Scanner;
public class DrivingCost
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
Scanner t = new Scanner(System.in);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
Scanner u = new Scanner(System.in);
System.out.print("Please enter the price per gallon (dollars): ");
String distanceInMiles = s.nextLine();
System.out.println("The distance (miles): " + distanceInMiles);
String fuelEfficiency = t.nextLine();
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
String pricePerGallon = u.nextLine();
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
}
}
This is the error I keep recieving:
DrivingCost.java:32: error: bad operand types for binary operator '/'
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
^
You're doing Math operation on String, you can't, you need double type
Double.parseDouble(sc.nextLine()); reads a line and parse to a double (benefits : avoid return line error in general, good habit to have)
sc.nextDouble() reads directly for a double
Use only one Scanner per source
Have a good order between print and scanner asking
Scanner sc = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
String distanceInMiles = Double.parseDouble(sc.nextLine());
System.out.println("The distance (miles): " + distanceInMiles);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
String fuelEfficiency = Double.parseDouble(sc.nextLine());
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
System.out.print("Please enter the price per gallon (dollars): ");
String pricePerGallon = Double.parseDouble(sc.nextLine());
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
You are trying to do calculations with strings. You have to parse doubles out of your string inputs. Just change your equation line to this:
double tripCost = (Double.valueOf(distanceInMiles) / Double.valueOf(fuelEfficiency)) * Double.valueOf(pricePerGallon);
P.S. Proper input validation would be a good improvement. In case user provide incorrect input. Also, as mentioned in the comments there is no need to use multiple Scanners. One will be enough.
You can get distanceInMiles, fuelEfficiency and pricePerGallon in double using s.nextDouble().
After that you should be able to perform double operation on these variables.
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
double distanceInMiles = s.nextDouble();
System.out.println("The distance (miles): " + distanceInMiles);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
double fuelEfficiency = s.nextDouble();
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
System.out.print("Please enter the price per gallon (dollars): ");
double pricePerGallon = s.nextDouble();
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
}
This is a loan calculator program. I'm having trouble with the math. Everything else seems to be correct except for the value of the beginning balance after 2 months. Notice that the beginning balance of the 3rd month is different from the ending balance of the 2nd month. Same thing for the succeeding months. I've been trying to fix it but everything didn't work out. I need them to be the same so the ending balance of the last month will be 0.
This is a sample output of the program:
Personal Loan Payment Calculator
Enter a loan amount: 1000
Enter the loan term (months): 6
Enter the interest rate (% per year): 9
Loan Payment and Amortization Table
Months Beginning Monthly Principal Interest Ending
Balance Payment Paid Paid Balance
1 1000.00 171.07 163.57 7.50 836.43
2 836.43 171.07 164.80 6.27 671.64
3 670.41 171.07 166.04 5.03 504.37
4 501.88 171.07 167.30 3.76 334.57
5 330.78 171.07 168.59 2.48 162.19
6 157.06 171.07 169.89 1.18 -12.83
Summary:
========
Loan Amount: $1,000.00
Monthly Payment: $171.07
Number of Payments: 6
Total Interest Paid: $24.00
Annual Interest Rate: 9.00%
This is the program:
public class LoanCalculator {
public static void main(String[] args) {
System.out.println("Personal Loan Payment Calculator"); // print the name of the program
System.out.println("================================");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
String badInput; // assign non-integer or non-double inputs to badInput
System.out.print("Enter a loan amount: "); // prompt the user to enter loan amount
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected a Double, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double loanAmount = keyboard.nextDouble(); // assign the first input to loanAmount
System.out.print("Enter the loan term (months): "); // prompt the user to enter number of months
while ( ! keyboard.hasNextInt()) // is the second input value an int?
{
badInput = keyboard.next();
System.out.println("Error: expected an Integer, encountered: " + badInput);
System.out.println("Please enter a loan term in Integer: ");
}
int loanTerm = keyboard.nextInt(); // assign the second input to loanTerm
System.out.print("Enter the interest rate (% per year): "); // prompt the user to enter the interest rate
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double interestRate = keyboard.nextDouble(); // assign the third input to interestRate
System.out.println(); // skip a line
System.out.println(" Loan Payment and Amortization Table");
System.out.printf("%s", "=============================================================");
System.out.println();
System.out.printf("%5s %10s %10s %10s %10s %10s", "Months" ,"Beginning", "Monhtly", "Principal", "Interest", "Ending");
System.out.println();
System.out.printf(" %5s %10s %10s %10s %10s %10s", "#","Balance", "Payment", "Paid", "Paid", "Balance");
System.out.println();
System.out.printf("%s ", "=============================================================");
System.out.println();
double monthlyRate = (interestRate / 100.0) / 12.0;
double monthlyPayment = (monthlyRate * loanAmount) / ( 1 - (Math.pow( 1 + monthlyRate, - loanTerm)));
double beginningBalance = loanAmount;
double interestPaid = beginningBalance * monthlyRate;
double principalPaid = monthlyPayment - interestPaid;
int total_interest_paid = 0;
for (int monthCount = 0 ; monthCount < loanTerm ; ++monthCount)
{
int months = 1 + monthCount;
beginningBalance = loanAmount - principalPaid * monthCount;
interestPaid = beginningBalance * monthlyRate;
principalPaid = monthlyPayment - interestPaid;
double endingBalance = beginningBalance - principalPaid;
System.out.printf(" %5d %10.2f %10.2f %10.2f %10.2f %10.2f\n", months, beginningBalance, monthlyPayment, principalPaid, interestPaid, endingBalance);
total_interest_paid += interestPaid;
}
System.out.printf("%s ", "=============================================================");
System.out.println();
NumberFormat currency = NumberFormat.getCurrencyInstance();
DecimalFormat percentFormat = new DecimalFormat ("0.00");
System.out.println("\nSummary:");
System.out.println("========");
System.out.println("Loan Amount: " + currency.format(loanAmount));
System.out.println("Monthly Payment: " + currency.format(monthlyPayment));
System.out.println("Number of Payments: " + loanTerm);
System.out.println("Total Interest Paid: " + currency.format(total_interest_paid));
System.out.println("Annual Interest Rate: " + percentFormat.format(interestRate) + "%");
}
}
The error is very simple:
beginningBalance = loanAmount - principalPaid * monthCount;
Remember that "principalPaid" increases every month. The total principal paid is not the last principalPaid * mouthCount but the sum of the principal paid in all months.
You could create a running total for principalPaid like you did for interest paid.
But it would be much easier to do beginningBalance = previous month endingBalance.
I'm writing a program used to calculate the total sales of employees in a small business, and am trying to figure out how to restart the program based on a user input of y/n. I know that loops are what I need to use here, but need a push in the right direction.
Code:
import java.util.Scanner;
public class calcMain {
public static void main(String[]args){
double totalPay = 0, itemOne = 239.99, itemTwo = 129.75, itemThree = 99.95, itemFour = 350.89, commission;
int weeklyBonus = 200, numSold;
String employee1, employee2, employee3, employee4, yn;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the salesperson's name: ");
employee1 = kb.nextLine();
System.out.println("Please enter the number of Item 1 sold: ");
numSold = kb.nextInt();
totalPay += (itemOne * numSold);
System.out.println("Please enter the number of Item 2 sold: ");
numSold = kb.nextInt();
totalPay += (itemTwo * numSold);
System.out.println("Please enter the number of item 3 sold: ");
numSold = kb.nextInt();
totalPay += (itemThree * numSold);
System.out.println("Please enter the number of item 4 sold: ");
numSold = kb.nextInt();
totalPay += (itemFour * numSold);
System.out.println("The total weekly earnings for " +employee1+ " are: " +totalPay);
System.out.println("Would you like to input the sales of another employee? (y/n)");
yn = kb.next();
}
}
Put all the code inside a while loop that says while (yn.equalsIgnoreCase("y"))
Don't forget to initialize yn to y!
Second solution:
Modify the code so that it returns a string, and if the user inputs y, return y, or if the user inputs n, return n.
Put all that code inside a method (lets call it method x for now)
public static void main(String[] args) {
while(x().equalsIgnoreCase("y")){}
}
Using a do-while loop (while loop should have the same effect) and ask for (y/n) at the end.
Like this:
String yn;
do
{
// Your code here
// Ask for confirmation
}
while (yn.equals("y"));
I have two programs:
Score.java set to do the following:
read scores from the keyboard and print their average.
The scores will be numeric and may include a decimal part.
For example a score might be 8.73 or some such. Different contests will have different numbers of judges. It will keep asking for and reading in scores until the user types 'done'. The program will then print the total score, the number of scores and the average score. The program will then prompt the user to see if there are any more contestants. If there are begin prompting for scores again. If there are no more then exit the program." I have it set to stop the program when you enter "N", and set to add future entries to the calculation after entering "Y".
import java.util.Scanner;
// This is the Score program
// Written by me
public class Score
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = sum + num;
cnt = cnt + 1;
System.out.print("enter number: ");
ans = game.next();
}
System.out.println(cnt);
System.out.println(sum);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
While the above process works, I cannot get my second program, Olympic.java, to work properly after typing "Y" to add more scores. Instead, it starts a whole new calculation of average instead of adding to the previous calculations:
import java.util.Scanner;
// This is the Olympic program
// Written by me
public class Olympic
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
double highscore = Double.MAX_VALUE;
double lowscore = Double.MIN_VALUE;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
lowscore = game.nextDouble();
highscore = game.nextDouble();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = (sum + num) - lowscore - highscore;
cnt = cnt + 1;
System.out.print("enter number: ");
if (num > highscore)
{
highscore = num;
}
if (num < lowscore)
{
lowscore = num;
}
ans = game.next();
}
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
So I did a really quick test
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
while (true) {
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
System.out.println("I'm free");
}
And this will exit fine.
As to your second problem. I think your logic is a little skewed. You could try something like...
Scanner game = new Scanner(System.in);
double num = 0;
double sum = 0;
int cnt = 0;
while (true) {
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
double lowscore = Double.MAX_VALUE;
double highscore = 0;
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done")) {
num = Double.parseDouble(ans);
lowscore = Math.min(lowscore, num);
highscore = Math.max(highscore, num);
sum += num;
cnt++;
System.out.print("enter number: ");
if (num > highscore) {
highscore = num;
}
if (num < lowscore) {
lowscore = num;
}
ans = game.next();
}
sum -= lowscore;
sum -= highscore;
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
This will output...
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 2
enter number: 3
enter number: 4
enter number: 5
enter number: 6
enter number: 7
enter number: 8
enter number: 9
enter number: 10
enter number: done
Throwing out low score 1.0 and high score 10.0
Total Score 44.0 count scores 10 avg score 4.4
Enter another contestant (Y/N)?
y
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 12
enter number: 13
enter number: 14
enter number: 15
enter number: 16
enter number: 17
enter number: 18
enter number: 19
enter number: 20
enter number: done
Throwing out low score 1.0 and high score 20.0
Total Score 168.0 count scores 20 avg score 8.4
Enter another contestant (Y/N)?
n
As to your exception. When using Scanner.nextDouble, it will throw an exception if the input is not parsable as a double. You will need to deal with this situation as you see fit...