-1
我開始瞭解更多關於Java的知識,我正在嘗試編寫一個帶有用戶輸入的小費計算器,並顯示小費佔總數的10%和20% 。我收到了一個無法解析的「無法對非靜態方法進行靜態引用」錯誤。Java基本面向對象的小費計算器
小費類:
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));
}
}
任何幫助,將不勝感激。謝謝!
錯誤是哪一行?這會有很大的幫助。 –
我的原始錯誤是在第36行float value = askForInput();執行一些回覆後,第15行出現新的錯誤(無法解析爲變量) –