Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here's the question I was asked:
Write a complete Java program called CalcTotalPrice. The program must include five methods:
getSaleTotal, getSalePrice, getSaleWeight, calcTax, and calcShipping.
getSaleTotal takes no input parameters and returns a double, which is the sale total, and which it computes by calling the other four methods.
getSalePrice returns a double, which it gets from the user at the command line.
getSaleWeight returns a double, which it gets from the user at the command line.
calcTax takes a double as a parameters (the sale price) and returns the tax amount as a double (use 6% as a fixed tax rate).
calcShipping takes a double as a parameter (the sale weight) and returns the shipping amount as a double (calculate shipping as $10 if weight is less than 10 and $20 if weight is 10 or greater).
getSaleTotal should print the sale price amount, tax amount, shipping amount, and sale total amount to the command line.
nothing will print in the compiler. Please help me.
Here's my code:
import java.util.Scanner;
/**
*
* #author Kramer1
*/
public class CalcTotalPrice {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public static double getSaleTotal(){
Scanner in = new Scanner(System.in);
double price = getSalePrice(in);
System.out.println(price);
double tax = calcTax(.06);
System.out.println(tax);
double shipping = calcShipping(in.nextDouble());
System.out.println(shipping);
double saleTotal = ((price)*tax)+price+shipping;
System.out.println(saleTotal);
return saleTotal;
}
public static double getSalePrice(Scanner in){
double salePrice = in.nextDouble();
return salePrice;
}
public static double getSaleWeight(Scanner in){
double saleWeight = in.nextDouble();
return saleWeight;
}
public static double calcTax(double salePrice){
double salesTax = .06;
return salesTax;
}
public static double calcShipping(double saleWeight){
double amountShipping = 0;
if (saleWeight < 10){
amountShipping = 10.;
}else if(saleWeight > 10){
amountShipping = 20.;
}
return amountShipping;
}
}
You arent doing anything in your main()
To see the output, you will have to create the Scanner in main and then call appropriate methods.
You need to do some code refactoring. First, move your Scanner to the main method. Then pass it around as an argument to other methods to read data from or read data in main and pass the values directly. I suggest the latter
You also need to declare the variables you use outside the methods and into the class so that their values persist till the end of the program and you will have access to them in various methods. Do declare them static.
You have a main method that is empty - it is not doing anything or calling any code.
Try instantiating your class and calling some methods in it.
it also looks like it is expecting some input from the user. So also try instantiating a Scanner class in your main which can then be passed to some methods. Remember to also call in.nextLine(); to flush the input before calling the next in.nextDouble();
try
Static Double salesPrice = null;
public static void main(String[] args) {
CalcTotalPrice ctp = new CalcTotalPrice ();
Scanner sc = new Scanner(System.in);
salesPrice = ctp.getSalesPrice (in);
in.nextLine();
//etc
}
Related
I am trying to make a simple android app that can add and subtract numbers, but my challenge is to make sure that the program is Object-Oriented. Currently I have been told that it is linear, but I am confused as to how it has remained linear after trying many times to make it object-oriented. How can I make this object oriented programming. Here is my code.
import java.util.Scanner;
public class addNumbers {
public static void main(String[] args)
{ // Begin main
Scanner input = new Scanner( System.in ); // Instantiate object input
System.out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
System.out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
double sum=number1 + number2; // Add the numbers
double difference = number1 - number2; // Subtract number 2 from number1
System.out.printf("\nSum = %f\n", sum); // Print the sum
System.out.printf("Difference = %f", difference); // Print the difference.
}
} // end main
My applications use this boilerplate to execute inside an object. If you start like this, you can add methods as you need them.
public class Demo
{
public static void main (String[] args)
{
final Demo app = new Demo ();
app.execute ();
}
private void execute ()
{
// Do stuff here.
}
}
Whoever gave you this assignment is using wrong and confusing terms, because linear programming is something else. But that's a different topic.
Even though this program is not complex, we can introduce some classes by modelling the flow of the program and/or the math operations.
Here is one idea... we could have a class called Operands, that has a method to read the numbers from the input while it prints instructions to the output. Then it stores these two numbers.
So something like this (I am using static class here instead of just class in case you will put this inside your public class addNumbers)
static class Operands {
public final double first;
public final double second;
public Operands(double first, double second) {
this.first = first;
this.second = second;
}
public static Operands readFromIO(InputStream in, PrintStream out) {
Scanner input = new Scanner(in); // Instantiate object input
out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
return new Operands(number1, number2);
}
}
Then we could have another class called Calculator, that has a method to set the operands setOperands(Operands operands) and two methods to get the results for the sum and the difference. The methods could be called getSum and getDifference.
static class Calculator {
private double sum = 0;
private double difference = 0;
public void setOperands(Operands operands) {
sum = operands.first + operands.second;
difference = operands.first - operands.second;
}
public double getSum() {
return sum;
}
public double getDifference() {
return difference;
}
}
Then in the main method of the program, we just need to make an instance of the Calculator class and set the Operands on the instance. We read these operators by calling Operands.readFromIO(...). Then we retrieve the sum and the difference from the calculator instance.
So the code in main looks like this
public static void main(String[] args) {
Calculator c = new Calculator();
Operands operands = Operands.readFromIO(System.in, System.out);
c.setOperands(operands);
System.out.printf("Sum = %f\n", c.getSum()); // Print the sum
System.out.printf("Difference = %f\n", c.getDifference()); // Print the difference.
}
This is just one way to do it with some objects.
Another way could be to use an interface called Operation that contains a calculate(Operands operands) method and have 2 more classes Addition and Subtraction implement the interface. Then you would use those two classes to calculate the results.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Create a class studentBilling() that includes three return overloaded calculateBill() methods as follows:
The first calculateBill() method will receive the tuition fees as single parameter. Add 14% tax to the tuition fees and return the total due.
The second calculateBill() method receives the tuition fees and the cost of textbooks. Add the two values and then add 14% tax and return the total due.
The third calculateBill() method receives the tuition fees, textbook costs and a coupon value. Add the tuition and cost of textbooks and subtract the coupon value. Add 14% tax and return the total due.
Write a program billTesting that tests all three overloaded methods.
Create a new studentBilling object.
Create a Scanner object to enter the tuition fees, textbook costs, and the coupon value.
Call the three methods and display the results.
my solution
package student;
import java.util.Scanner;
/**
*
* #author FASA
*/
public class Student {
double totalDue;
static Scanner fees = new Scanner(System.in);
double Student;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner fees = new Scanner(System.in);
System.out.println(CalculateBill1());
System.out.println(CalculateBill2());
System.out.println(CalculateBill3());
}
public static double CalculateBill1 (double totalDue, double tax, double fees) {
tax = 0.14;
return (totalDue);
}
public double CalculateBill2 (double fees, double textBookFees) {
double tax = 0.14;
Student = fees + textBookFees + tax;
return (totalDue);
}
public double CalculateBill3 (double tax, double fees, double textBookFees, double couponValue) {
Student = fees + textBookFees - couponValue + tax;
return (totalDue);
}
}
It wont print the bill, please help
I am not going to help you with the complete solution as it seems to be your homework ;)
You should get compilation error on lines System.out.println(CalculateBill1());
System.out.println(CalculateBill2());
System.out.println(CalculateBill3()); because there is no method with definition as void parameter.
you need to pass appropriate parameters to call these methods. For example to call method "CalculateBill1 (double totalDue, double tax, double fees)" you need to call it like below:
System.out.println(CalculateBill1(1.25,5.23,6.0));
Hope this help.
I am brand new to Java, started two weeks ago and am having issues wrapping my mind around this issue. I have a problem in a class I am taking that has been brought up before. Converting kilograms to pounds and rounding to the second decimal place.
I can create the input side of things and bring up a dialog box to prompt the user to enter in a weight. I can also create an output that uses an equation I made to output the answer in a dialog box.
My question is how do I take the information that is input and use it to convert from kilograms to pounds?
I have been reading my book and scouring the internet trying to find an answer and I think I may be over thinking it. Thanks for the help.
Input.java:
//This program asks a user to input a weight in kilograms.
package module2;
import javax.swing.*;
public class Input {
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
}
}
Output.java:
//This program outputs a converted weight from kilograms to pounds.
package module2;
import javax.swing.JOptionPane;
public class Output {
public static void main(String[] args) {
double kg = 75.5;
double lb = 2.2;
double sum;
sum = (kg * lb);
JOptionPane.showMessageDialog(null,sum, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
}
}
Right now you have 2 main methods. Both of these are entry points for the program. Since they have to share information, it doesn't make sense you have both.
What I'd recommend is to change the Output's main method to a instance method, taking one parameter: the weight from the Input.
Like so:
public void printOutput(final double weight){
//...
}
You can then call that from the Input's main method like so:
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
double kg = Double.parseDouble(weight); // Be sure to parse the weight to a number
Output output = new Output(); // Create a new instance of the Output class
output.printOutput(kg); // Call our method to display the output of the conversion
}
One other thing, is that since Output is currently only used for that one method, you could consider just moving that method into Input.
// addition of two integers using JOptionPane
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sumof two Integers", JOptionPane.PLAIN_MESSAGE);
}
}
Iam doing a school assignment in Java, and I need some help to do some calculations in a method. Iam used to PHP, and I've appended a lot of my knowledge in the code, but this one I just cant figure out (I know how do do it without the function, but that requires much more lines of code which is stupid).
Here is some of my code:
public static void main (String[] args) {
// User inputs
calculate("Number of beers", 20, 1.50);
}
public static void calculate(String articleName, double numberOfX, double pricePerUnit) {
double subTotal = numberOfX * pricePerUnit;
System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal);
}
This prints out a nice bill of the things I've bought. Furthermore I would like this method to add the totalprice to a (global?) variable which eventually shows the final price of all items. In PHP i usually wrote a variable named totalDue += subTotal;
Is there any way to do this in java? I would be a shame to write an entire new function to do the math if I just could add the total price of each item into a variable.
Global variables don't exist in Java.
And this is not how it should be done. Rather than the method updating some variable, the method should just return the result of the computation, and the caller should be responsible of using the result as he wants to:
double total = 0D;
total += calculate("Number of beers", 20, 1.50);
total += calculate("Number of pizza", 10, 8);
// ...
This way, you won't have to change anything in the calculate method when you'll want to compute subtotals, or averages, or anything. One method = one responsibility.
This should be true for your PHP programs as well.
After this is done, you should encapsulate the article name, number of items, and unit price in a class, and add methods to the class, like toString (to display the bought item), and computePrice (to compute the price of this bought item).
public static void main (String[] args) {
// User inputs
double total = 0.0;
total += calculate("Number of beers", 20, 1.50);
}
public static double calculate(String articleName, double numberOfX, double pricePerUnit) {
double subTotal = numberOfX * pricePerUnit;
System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal);
return subTotal;
}
I am really new to programming, on netbeans i have deleted all the other text, all i have is the following, Why wont the program run?
The error i get is, no main Class found.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package findcost2;
public class Main
/* a program to calculate and display the cost of a product after
* sales tax has been added*/
public class FindCost2
Public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
Try this exactly and name your java file FindCost2.java
package findcost2;
public class FindCost2{
public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
You're missing a curly bracket after class Main and you have two public classes in the same source file. Delete public class Main and change Public to public.
You should probably also use decimal numbers for dealing with currencies
Sooner or later, everyone trying to calculate money in Java discovers that computers can't add.
Why is Public capitalized? Shoud be:
public class FindCost2 {
public static void main(String[] args) { ... }
}
Numerous problems with this code:
The outer class (Main) does not have an opening bracket. Insert the { bracket.
The inner class (FindCost2) does not have an opening bracket. Insert the { bracket.
The public modifier for the main method is capitalized. Start with a lowercase p.
The main method is nested in an inner class. This is really bad form. To make it work anyway, the inner class needs to be static. Insert the static keyword.
When put like this, it compiles:
public class Main {
/*
* a program to calculate and display the cost of a product after sales tax
* has been added
*/
public static class FindCost2 {
public static void main(String[] args) {
double price, tax;
price = 500;
tax = 17.5;
price = price * (1 + tax / 100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
}
However, there is absolutely no point to the outer class (Main). Just delete this. When the outer class is removed, the inner class (FindCost2) need not be static anymore. Remove the keyword.
It is really bad form to declare multiple variables on one line (as in double price, tax;). Split that to two lines:
double price;
double tax;
There are good reasons not to use the double type for monetary values. With a little extra work, you can easily write a simple Money class. Check javapractices.com for a good overview on that.
Hope that helps!