我正在寫一個程序,從用戶的名稱,日期和數字,他們輸入它的次數,然後加起來輸入的數字。如果你看第三個循環,你會看到我想添加的位置。我嘗試過總= cust [i] .amount + total;但由於某種原因,我無法訪問金額。需要添加從一個對象的數字
這是一項任務。(我知道不應該張貼在這裏寫作業的問題,但我很爲難。)唯一的數據成員的客戶是有是名
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 9999;
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt;
double total = 0;
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press 9");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
}
for(int i=0; i < cnt; i++){
total = cust[i].amount + total;
}
s.close();
}
}
interface Functions {
public void getData();
public void showData();
}
abstract class Customer implements Functions {
protected String name;
}
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
}
class Service extends Customer {
protected String date;
protected double amount;
public Service() {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
可能重複的[爲什麼我得到一個錯誤!?(空指針異常)](http://stackoverflow.com/questions/21446262/why-am-i-getting-an-errornull-pointer-exception) –
這是一個不同的問題...相同的代碼,是的。 – user278153
不相關,但'for'循環中存在一個細微的錯誤。它需要'for(cnt = 0; cnt