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!
Related
I have a class where I have to manually create a UML diagram for the program below. In order to understand better, I automatically created a UML diagram in Eclipse with ObjectAid.
I have a few questions I would like to understand:
Of the three sections class, attributes, and methods, why is "PayrollDialog()" included in the methods section? Is it because you should always include the default constructor?
Are JOptionPane.showInputDialog really not considered for the methods section? Why not? I ask because I notice getting the user name, hours worked, and pay rate are not included.
Are there really no attributes to be listed in the UML for this program? I think this is correct because they are not listed under the public class PayrollDialog.
Is the UML diagram listed really accurate for this program? If not, what should it look like? I find it hard to believe the assignment is that simple.
import javax.swing.JOptionPane;
/**
4 * This program demonstrates using dialogs
* with JOptionPane.
*/
public class PayrollDialog
{
public static void main(String[] args)
{
String inputString; // For reading input
String name; // The user's name
int hours; // The number of hours worked
double payRate; // The user's hourly pay rate
double grossPay; // The user's gross pay
// Get the user's name.
name = JOptionPane.showInputDialog("What is " +
"your name? ");
// Get the hours worked.
inputString =
JOptionPane.showInputDialog("How many hours " +
"did you work this week? ");
// Convert the input to an int.
hours = Integer.parseInt(inputString);
// Get the hourly pay rate.
inputString =
JOptionPane.showInputDialog("What is your " +
"hourly pay rate? ");
// Convert the input to a double.
payRate = Double.parseDouble(inputString);
// Calculate the gross pay.
grossPay = hours * payRate;
// Display the results.
JOptionPane.showMessageDialog(null, "Hello " +
name + ". Your gross pay is $" +
grossPay);
// End the program.
System.exit(0);
}
}
Yes you are basically correct.
JOptionPane is not listed in the Class Diagram because it is found in javax.swing.JOptionPane and its not globally declared as property/attribute or method of your PayrollDialog class.
Based on your source code, there are no global properties/attribute declared.
For example
class PayrollDialog{
static JFrame f; // this would appear as property in UML
public static void main(String[] args){..}
}
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);
}
}
I am learning Java and am working on a basic program where a user can input a cost figure, an inflation percentage and a time (years) in order to calculate a cost including inflation.
I am using three classes, 1 application class, 1 driver class and 1 singular class. I am doing this as per the book to build OOP skills (I know there are simpler procedural / structured methods but that is not the point of my exercise).
The issue I am having that the output answer is $0 regardless of the figures I enter. This should not be the case obviously. If someone could please skim over my code and point me in the right direction I would be grateful.
Application Class:
package priceestimator;
public class PriceEstimator {
public static void main(String[] args) {
CostCalculator CostCalc = new CostCalculator();
CostCalc.calculateCost();
}
}
Driver Class:
public class CostCalculator {
public void calculateCost(){
Calculator calculator = new Calculator();
calculator.calculator();
Calculator years = new Calculator();
years.years();
Calculator inflation = new Calculator();
inflation.inflation();
Calculator price = new Calculator();
price.price();
}
}
Singular Class:
package priceestimator;
import java.util.Scanner;
public class Calculator {
private Scanner myScanner = new Scanner(System.in);
private double cost;
private double time;
private double costDif;
private void setTime(int time){
this.time = time;
}
private double getTime(){
return time;
}
private void setCost(double cost){
this.cost = cost;
}
private double getCost(){
return cost;
}
private void setCostDif(double costDif){
this.costDif = costDif;
}
private double getCostDif(){
return costDif;
}
private void getMyScanner(){
this.myScanner = myScanner;
}
public void calculator(){
System.out.println("Enter the current cost (numbers only):");
cost = myScanner.nextDouble();
}
public void years(){
System.out.println("Enter the time difference in years:");
time = myScanner.nextDouble();
}
public void inflation(){
double costTimeDif;
double decimalConversion;
int percent = 100;
double input;
System.out.println("Enter the current inflation rate percentage (numbers only):");
input = myScanner.nextDouble();
decimalConversion = input / percent;
costTimeDif = time * decimalConversion;
costDif = cost * costTimeDif;
}
public void price(){
double price;
price = costDif + cost;
System.out.println("The estimated price is: $" + price);
}
}
Thanks for your time.
You're using different instances of Calculator in the calculateCost(). Use the same instance to get all the details and to calculate the final price as well.
public void calculateCost(){
Calculator calculator = new Calculator();
calculator.calculator();
calculator.years();
calculator.inflation();
calculator.price();
}
As you're using different instances, each instance has its own copy of the instance variables(which you're ultimately using to calculate the final price) and that's why for each instance only that particular value is being populated. Using the same instance would populate all the values by calling the various methods and thus, the price would be calculated using all the values entered by you via the different methods.
You have:
Calculator calculator = new Calculator();
calculator.calculator();
Calculator years = new Calculator();
years.years();
Calculator inflation = new Calculator();
inflation.inflation();
Calculator price = new Calculator();
price.price();
You are creating a different Calculator for every piece of information you input. Each of those is independent of the others. Instead, you mean:
Calculator calculator = new Calculator();
calculator.calculator();
calculator.years();
calculator.inflation();
calculator.price();
Each Calculator has its own copy of the instance fields (and they're initialized to 0 be default). Setting e.g. the time difference in one does not affect the time difference set in the others.
The objects you instantiate should reflect, conceptually, what you are trying to do. Was your intention to have 4 separate calculators? Or was your intention to have a single calculator with all of the information? Of course, it was the latter -- and your code should reflect that.
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
}
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;
}