Java基于面向对象的小费计算器

时间:2015-12-04 21:07:34

标签: java

我开始学习更多关于Java的知识,并且我正在尝试编写一个带有用户输入的小费计算器,并显示小费在%10和%20的总和。我得到一个单独的“无法对非静态方法进行静态引用”错误,我无法解决。

小费课程:

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;
}                   
}

使用主要方法的课程:

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));
    }

}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

askForInput()在您的类TestGrat中。但是,在main()中,您直接调用它,就好像它是静态的一样。你可能意味着:

TestGrat test = new TestGrat();
float value = test.askForInput();

askForInput()也返回无效,所以你可能也想修复它。