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;
}
}
Related
I'm having trouble using non static methods. I'm trying to get the value of my "side" variable from a method and plug them into another method which will calculate area. Is there a way to do this without changing the methods to static? None of the previously answered questions on here are helping and neither is my textbook.
import java.util.*;
public class CubeVolume
{
int side1;
int side2;
int side3;
public void getSides()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the length of side1");
side1 = input.nextInt();
System.out.println("Enter the length of side2");
side2 = input.nextInt();
System.out.println("Enter the length of side3");
side3 = input.nextInt();
}
public int getVolume(int side1, int side2, int side3)
{
int volume = side1 * side2 * side3;
return volume;
}
public static void main(String[] args)
{
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
}
I think the problem is with my method call cube.getVolume(side1, side2, side3); because the compiler tells me that non-static variable cannot be referenced from a static context.
If you want to use methods within main() then those methods must be static since main() is static. So you methods should be declared as:
public static void getSides() { .... }
public static int getVolume(int side1, int side2, int side3) { .... }
You can however avoid all this if you tell an instance of your class to start from a non-static method from within your main() method:
public static void main(String[] args) {
new CubeVolume().startApp(args);
}
private void startApp(String[] args) {
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
Now your other methods in the class do not need to be static since you're not calling them from static main().
There is no need to pass in any parameters to getVolume(), just use the class variables:
import java.util.Scanner;
class CubeVolume {
private int side1;
private int side2;
private int side3;
private void getSides() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of side1: ");
side1 = input.nextInt();
System.out.print("Enter the length of side2: ");
side2 = input.nextInt();
System.out.print("Enter the length of side3: ");
side3 = input.nextInt();
input.close();
}
private int getVolume() {
return side1 * side2 * side3;
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.valueOf(cube.getVolume());
System.out.println("The cubes volume is: " + cubeVolumeString);
}
}
Example Usage:
Cube Volume Calculator
======================
Enter the length of side1: 3
Enter the length of side2: 4
Enter the length of side3: 5
The cube's volume is: 60
Alternative approach which stores the side lengths in a double array, sides, and deals with possible invalid input in getSides():
import java.util.Scanner;
class CubeVolume {
private double[] sides;
CubeVolume() {
sides = new double[3];
}
private void getSides() {
Scanner scanner = new Scanner(System.in);
int currentSide = 0;
while (currentSide < sides.length) {
System.out.printf("Enter the length of side %d: ", currentSide + 1);
double nextSide = 0.0;
input:
while (scanner.hasNext()) {
if (scanner.hasNextDouble()){
nextSide = scanner.nextDouble();
if (nextSide > 0) {
sides[currentSide] = nextSide;
break input;
} else {
System.out.println("ERROR: Input number was too small.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
}
} else {
System.out.println("ERROR: Invalid input, please input a number.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
scanner.next();
}
}
currentSide++;
}
scanner.close();
}
private double getVolume() {
return sides[0] * sides[1] * sides[2];
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.format("%.2f", cube.getVolume());
System.out.println("The cube's volume is: " + cubeVolumeString);
}
}
Example Usage 2:
Cube Volume Calculator
======================
Enter the length of side 1: a
ERROR: Invalid input, please input a number.
Enter the length of side 1: -1.1
ERROR: Input number was too small.
Enter the length of side 1: 3.4
Enter the length of side 2: 4.7
Enter the length of side 3: 5.8
The cube's volume is: 92.68
You need not to pass sides parameters to get valume function because your sides variable will be available to get valume function.
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.
First java class is the primary one which invokes other classes. I will copy the code for the two files. I cannot compile this code and I do not know why.
When I had the program in one file it ran fine, but the instructor wants it in two files. Can someone explain to me what I am doing, or did incorrectly?
File 1:
public class Wk2ToddFoughty {
public static void main(String[] args) {
SalaryCalc FinalSalaryCalc = new SalaryCalc();
FinalSalaryCalc.SalaryCalc();
}
}
File 2:
import java.util.Scanner;
class SalaryCalc {
Scanner in = new Scanner(System.in);
System.out.println("Enter your annual sales: $");
double sales = in.nextDouble();
double salary = 35000.00;
double commission = (sales * .015);
double totalSalary = salary + sales;
System.out.println("Your Salary + Commission is: $" + totalSalary );
}
It might be easier to understand if you kept to Java naming conventions - also see inline comments
public class Wk2ToddFoughty {
public static void main(String[] args) {
SalaryCalc myCalc = new SalaryCalc(); // SalaryCalc - name of class
// myCalc - name of object
myCalc.doCalc(); // doCalc - name of method (missing from your class)
}
}
// edit this class to add missing method
public class SalaryCalc {
public void doCalc () {
Scanner in = new Scanner(System.in);
System.out.println("Enter your annual sales: $");
double sales = in.nextDouble();
double salary = 35000.00;
double commission = (sales * .015);
double totalSalary = salary + sales;
System.out.println("Your Salary + Commission is: $" + totalSalary );
}
}
Your second file doesn't define a method called SalaryCalc. You should also honor standard Java naming practices, and keep input/output logic outside of your business classes.
import java.util.Scanner;
public class Wk2ToddFoughty {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter your annual sales: $");
SalaryCalc calc = new SalaryCalc(35000);
double totalSalary = calc.calcSalary(in.nextDouble());
System.out.println("Your Salary + Commission is: $" + totalSalary);
}
}
public class SalaryCalc {
private double salary;
public SalaryCalc(double salary) {
this.salary = salary;
}
public void calcSalary(double sales) {
double commission = sales * 0.015;
return salary + sales + commission;
}
}
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.
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());