I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.
Related
This assignment is to calculate the cost of a hospital visit. I am trying to ask the user what the prices for the "overnightCharge", "medicationCharge", and "labCharge" are. I then try to use the input to add them together in the method called "total". Next, I try to print the resulting/returned variable from "total" method in the main method by typing System.out.println("Your total charge is: " + total(totalCost). I thought total(totalCost) would retrieve the variable returned by "total" method.
package hospitalstay;
import java.util.Scanner;
/* total charges
if overnight charges
medication charges
lab charges
ask user if new patient*/
public class HospitalStay {
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
public static double overnightCharge () {// asking user for overnight charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your overnight charge");
double overnightCharge;
overnightCharge = sc.nextDouble();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your medication charge");
double medicationCharge;
medicationCharge = sc.nextDouble();
return medicationCharge;
}
public static double labCharge() {//asking user for lab charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your lab charge");
double labCharge;
labCharge = sc.nextDouble();
return labCharge;
}
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
double totalCost;
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicineCharge + labCharge); //Calculating all three charges
}
else {
totalCost = (medicineCharge + labCharge);
}
return totalCost;
}
}
You have changeŠ² the total method to
public static double total () {
return overnightCharge() + medicineCharge() + labCharge();
}
Also change main method to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total());
}
First of all, you've defined three parameters for method "total," but you are specifying only one argument in your main method:
total(totalCost)
to minimize the number of things that you need to change in your code, I would simply change the total() method to:
public static double total() {
double totalCost = overnightCharge();
totalCost += medicationCharge();
totalCost += labCharge();
return totalCost;
}
and in your main method:
public static void main(String[] args) {
System.out.println("Your total charge is: " + total();
}
You are passing the wrong inputs to total, change your main to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(medicationCharge(), labCharge(), overnightCharge()));
}
Also, in your total method, you don't need the if condition, so you can simplify it to:
public static double total(double medicineCharge, double labCharge, double overnightCharge) {
return (overnightCharge + medicineCharge + labCharge);
}
"Explanation why your code didn't work as desired: "
You have created a function total() which takes 3 arguments i.e (double medicineCharge, double labCharge, double overnightCharge)
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
return totalCost;
}
But when you are calling this function in your main() you are only passing it a single argument that is total(totalCost).
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
You have also made a typo mistake "medicineCharge"
You can try something like this to achieve your desired output :
import java.util.Scanner;
public class Hospital {
static Scanner input;
private static double overnightCharge, medicationCharge, labCharge,
totalCost;
public static double takeInput() { // single function to take input
input = new Scanner(System.in);
return input.nextDouble();
}
public static double overnightCharge() {// asking user for overnight charge
System.out.println("What is your overnight charge");
overnightCharge = takeInput();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication
// charge
System.out.println("What is your medication charge");
medicationCharge = takeInput();
return medicationCharge;
}
public static double labCharge() {// asking user for lab charge
System.out.println("What is your lab charge");
labCharge = takeInput();
return labCharge;
}
public static double total() {
overnightCharge();
medicationCharge();
labCharge();
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicationCharge + labCharge); // Calculating
// all
// three
// charges only when overnightCharge = 0
} else {
totalCost = (medicationCharge + labCharge);
}
return totalCost;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Total :" + total());
}
}
Note: I have also reduced the code for calling scanner again again.
import java.io.*;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Tuition
{
public static void main(String[] args)
{
//Declareing the variables
int credits;
double costPerCredit;
double tuition;
//calling methods
credits = getCredits();
costPerCredit = getCostPerCredit(credits);
tuition = calcTuition(credits, costPerCredit);
displayCredits(costPerCredit);
displayTotal(tuition);
//Dialog box that is popping out to ask the questions and get imput based on questions
JOptionPane.showMessageDialog(null, "Java Tuition Calculator Program");
}
public static int getCredits()
{
//declare hours variable
String input;
int credits = 0;
input = JOptionPane.showInputDialog(null,"Number of Credits?");
return credits;
}
public static double getCostPerCredit(int credits)
{
String input1;
double costPerCredit;
costPerCredit = credits * 107.78;
input1 = JOptionPane.showInputDialog(null,"Cost Per Credit?");
return costPerCredit;
}
public static double calcTuition(int credits, double costPerCredit)
{
double tuition;
tuition = credits * costPerCredit;
return tuition;
}
public static void displayCredits(double costPerCredit)
{
double credits;
credits = costPerCredit;
DecimalFormat twoDigits = new DecimalFormat("$#000.00");
System.out.println("Cost for Credits are " + credits);
}
public static void displayTotal(double tuition)
{
double total;
total = tuition;
DecimalFormat twoDigits = new DecimalFormat("$#000.00");
System.out.println("Your Tuition is " + total);
}
}
When I execute the code it should ask me to type the number of credits I am currently going to take and cost per credit. After I input those the total result should come up in a new window with the phrase "Cost for credits are *(the answer should come out from the equation "tuition = credits * costPerCredit;")*. That number result should be the number I put in the first dialog box multiping with the pre-set $107.78, and I want those answers to be in the new window that pops out in the end. But all i get is
Cost for Credits are 0.0
Your Tuition is 0.0
Why can't I get System.out.println to print out the answer from public static double getCostPerCredit(int credits) and public static int getCredits()? The dialog box pops up for both of them and asks the questions in the field but I want those answers to be printed out and not just result in the answer being "0.0".
Note: I took out String input1; and input1 = JOptionPane.showInputDialog(null,"Cost Per Credit?");. The code seems to work the same way w/o it but the dialog box is removed.
Can't get JOptionPane and System.out.println to work in tuition
calculator
First: Cost for Credits are 0.0 because of int credits = 0; and you return credits 0 as type int
Second: Any thing multiply by 0.0 is 0.0 as type double, So Your Tuition is 0.0
public static int getCredits()
{
//declare hours variable
String input;
int credits = 0;
input = JOptionPane.showInputDialog(null,"Number of Credits?");
return Integer.parseInt(input);
}
String input;
int credits = 0;
input = JOptionPane.showInputDialog(null,"Number of Credits?");
return credits;
credits is never changed. This code always returns 0.
I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());
import java.util.Scanner;
I am trying to turn this into a GUI program, and what I kind of came up with gives me a lot of errors, so if anyone could help me figure that out, that would be great.
public class Problemtwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the side: ");
double side = input.nextDouble();
double area = 3 * 1.73205 * side * side / 2;
System.out.println("The area " + area);
}
}
This is the GUI I tried to create
import java.swing.JOptionPane;
import java.lang.Math;
public class GUI_Problemtwo {
public static void main(String[] args) {
double side;
double area;
StringsideString = JOptionPane.showInputDialog("Enter the side: ");
return;
}
// Convert string to double
double side = Double.parseDouble(sideString);
double side = input.nextDouble();
// Compute the area
double area = 3 * 1.73205 * side * side / 2;
// Display results
String output = "The area is " + area;
}
I just know that I'm really doing something wrong. Also I have another GUI that I'm able to input into a dialog box, but I can't get it to pull up any output in a dialog box, it just looks like it doesn't even stop running...
import javax.swing.JOptionPane;
import java.io.*;
public class GUI_Account {
public static void main(String[] args)throws IOException {
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
double bal=0;
int month,i;
// Prompts user to enter a number of months
String MString = JOptionPane.showInputDialog("Enter number of months: ");
if (MString == null) {System.out.println("User prompt cancelled");
return;
}
month=Integer.parseInt(kb.readLine());
for(i=0;i<month;i++) {
bal=(bal+100)*1.00417;
}
// Convert string to double
double M =Double.parseDouble(MString);
// Display results in dialog box
String output = "The amount is " + bal; JOptionPane.showMessageDialog(null, output);
}
}
I need some help with a program for my programming class. It's a recursive program that takes a subtotal and a gratuity rate given by the user that outputs the full total and the gratuity cost. This is what I've got so far, and for some reason it just doesn't work:
import java.io.*;
import java.until.Scanner;
public class gratuity {
private double total;
private double subTotal;
private double gratRate;
private double newSubTotal;
private double newGratRate;
public static void main(String[] args) {
System.out.print("Enter the subtotal: ");
System.out.print("Enter the gratuity rate: ");
Scanner scan = new Scanner(System.in);
Scanner myScan = new Scanner(System.in);
double subtotal = scan.nextDouble();
double gratRate = myScan.nextDouble();
System.out.println("The Gratuity is: " + newSubtotal);
System.out.println("The Total is: " + Total);
}
public static double computeGratRate() {
double newGratRate = (gratRate/100);
return newGratRAte;
}
public static double computeNewSub() {
double newSubTotal - (subTotal * newGratRate);
return newSubTotal;
}
public static double computeTotal() {
double total = (newSubTotal + newGratRate);
return total;
}
}
If anyone would help me figure out how to fix it, I would be very grateful! Thank you!
A few things.
You are creating new variables called "subtotal" and "gratRate" in Main. These values override the member variables of the class.
Your problem won't compile anyway, because...
All your methods are static, which is OK, but these static methods are accessing non-static variables. Make all your member variables of this class static. (Or make everything outside of Main not static and then have "Main" be a stub to just create an instance of the gratuity class.
You need to import java.util.Scanner, not java.until.Scanner.
This line is a compiler error:
double newSubTotal - (subTotal * newGratRate);
I think you mean:
double newSubTotal = (subTotal * newGratRate);
That should be enough hints for now.... keep trying.
Did you mean:
import java.util.Scanner;
public class Gratuity {
private double subTotal;
private double gratRate;
public static void main(String[] args) {
Gratuity gratuity = new Gratuity();
System.out.print("Enter the subtotal: ");
Scanner scan = new Scanner(System.in);
gratuity.setSubTotal(scan.nextDouble());
System.out.print("Enter the gratuity rate: ");
Scanner myScan = new Scanner(System.in);
gratuity.setGratRate(myScan.nextDouble());
System.out.println("The new GratRate is: " + gratuity.getNewGratRate());
System.out.println("The New Sub is: " + gratuity.getNewSub());
System.out.println("The Total is: " + gratuity.getTotal());
}
public double getNewGratRate() {
return gratRate/100;
}
public double getNewSub() {
return getNewGratRate() * subTotal;
}
public double getTotal() {
return getNewSub() + getNewGratRate();
}
public double getSubTotal() {
return subTotal;
}
public void setSubTotal(double subTotal) {
this.subTotal = subTotal;
}
public double getGratRate() {
return gratRate;
}
public void setGratRate(double gratRate) {
this.gratRate = gratRate;
}
}