How to sum value in a specific object? - java

I have this code where you would search for the patient ID and when found a sub menu will show, the user would then be prompted to choose. If the user chooses bill the would then be asked to enter a transaction and it would be summed to the balance in the same object as the ID that was searched. However when the user inputs a value it always sums the value to the balance(450) in the object.
How can I fix this?
NB: it's in an array
output: adds the input to the first object only.
patient pAccount[] = new patient [10];
patient p1 = new patient("Jabari","luck",d1 ,"234-4343", "p01" ,450);
patient p2 = new patient("Lisa", "nun", d2,"311-5634" , "p02",300);
patient p3 = new patient("Kyle", "Hep",d3 ,"555-5555" , "p03",2000 );
//search array for patient ID
public static void ID(person [] pAccount) {
Scanner scan= new Scanner(System.in);
String num = scan.next();
for(int i=0; i< pAccount.length; i++) {
if (pAccount[i].getpatID().equals(num)) {
System.out.println("found");
break;
}
}
}
//sum user input to balance
public static void bill(person[] pAccount) {
Scanner in = new Scanner (System.in);
double sum;
double num= in.nextDouble();
for(int i=0; i <= pAccount.length; i++) {
person ad= pAccount[i];
sum = ((patient) ad).getbalance()+ num;
System.out.println("Balance: " +sum);
break;
}
}```

what I understood from your question is, you need to add sum to the balance of a specific object in Patient Object array. Below is the way to do,
(I excluded few member variables which I didn't get just by looking at Object creation in your question and kept only name, patId and balance in Patient Class. Also I assumed you've Constructor with all the fields)
I took your code and modified a little for you requirement. You can refer comments I added in the code snippets.
PatientMainClass.class
public class PatientMainClass {
public static void main(String[] args) {
Patient pAccount[] = new Patient[3];
Patient p1 = new Patient("Jabari", "p01", 450);
pAccount[0] = p1;
Patient p2 = new Patient("Lisa", "p02", 300);
pAccount[1] = p2;
Patient p3 = new Patient("Kyle", "p03", 2000);
pAccount[2] = p3;
//Use bill method to add Amount to existing balance of all the Patient Objects
Patient.bill(pAccount);
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to the Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
System.out.println();
//Use billToSpecific method to add Amount to specific Patient Object
//to billToSpecific method, pass both Patient Array and Patient ID to which you want to add Amount
Patient.billToSpecificPatient(pAccount, "p02");
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to p02, Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
} }
Patient.class
public class Patient {
private String name;
private String patId;
private double balance;
public Patient(String name, String patId, double balance) {
super();
this.name = name;
this.patId = patId;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatId() {
return patId;
}
public void setPatId(String patId) {
this.patId = patId;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
// This method will Add entered value i.e.. "num" to the Balance of all the Patient Objects
public static void bill(Patient[] pAccount) {
System.out.println("In bill method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
// break; // Commenting break statement to add balance to all the Objects
}
}
// This method will Add entered value i.e.. "num" to the Balance of the Specific Patient Object
public static void billToSpecificPatient(Patient[] pAccount, String patId) {
System.out.println("In billToSpecific method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
if (pAccount[i].getPatId().equals(patId)) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
break; // Using break statement to exit the loop once we add amount to specific Patient Object
}
}
} }
I guess, you can now resolve your issue with the help of these code snippets. Hope it is helpful.

Related

How do I update the element inside the arraylist?

public class billing{
private int id;
//File f=new File("C:/Users/Bingus/Documents/Projects/accounts.txt");
private String bc;
private String bd;
private String customerName;
private String customerAddress;
private String customerNumber;
private String periodT;
private String periodF;
private double presentR;
private double previousR;
private double previousB;
private double dueTotal;
private static ArrayList<Account> accountList = new ArrayList<>();
public billing(int id,String bc,String bd,String customerName,String customerAddress,String customerNumber,String periodT,String periodF,double presentR,double previousR,double previousB,double dueTotal){
this.id = id;
this.bc = bc;
this.bd = bd;
this.customerName = customerName;
this.customerAddress = customerAddress;
this.customerNumber = customerNumber;
this.periodT = periodT;
this.periodF = periodF;
this.presentR = presentR;
this.previousR = previousR;
this.previousB = previousB;
this.dueTotal = dueTotal;
}
public int getId(){
return id;
}
public String getBc(){
return bc;
}
public String getBd(){
return bd;
}
public String getCustomerName(){
return customerName;
}
public String getCustomerAddress(){
return customerAddress;
}
public String getCustomerNumber(){
return customerNumber;
}
public String getPeriodT(){
return periodT;
}
public String getPeriodF(){
return periodF;
}
public double getPresentR(){
return presentR;
}
public double getPreviousR(){
return previousR;
}
public double getPreviousB(){
return previousB;
}
public double getDue(){
return dueTotal;
}
public static void main(String[] args){
Scanner scanner = new Scanner (System.in);
Scanner kb = new Scanner (System.in);
int user_choice;
int x = 0;
do{
System.out.println();
System.out.println("1) New Billing");
System.out.println("2) Add Existing Billing");
System.out.println("3) View Billing Account ID");
System.out.println("4) View By Date");
System.out.println("5) Update Existing Billing");
System.out.println("6) Delete Billing Account");
System.out.println("7) Display All Account");
System.out.println("8) Exit");
System.out.println();
System.out.print("Enter choice [1-8]: ");
user_choice = scanner.nextInt();
switch (user_choice){
case 1:
int min = 1000;
int max = 9999;
int randomStr = (int)(Math.random() * (max - min + 1) + min);
int id = randomStr;
System.out.println("Your Account Number is : " + id);
System.out.print("Enter Billing Code: ");
String bc = scanner.next();
System.out.print("Enter Billing Date(dd/mm/yyyy): ");
String bd = scanner.next();
System.out.print("Enter Customer Name: ");
String customerName = kb.nextLine();
System.out.print("Enter Customer Address: ");
String customerAddress = kb.nextLine();
System.out.print("Enter Customer Number: ");
String customerNumber = scanner.next();
System.out.print("Enter Period To: ");
String periodT = scanner.next();
System.out.print("Enter Period From: ");
String periodF = scanner.next();
System.out.print("Enter Present Reading: ");
double presentR = scanner.nextDouble();
System.out.print("Enter Previous Reading: ");
double previousR = scanner.nextDouble();
System.out.print("Enter Previous Balance: ");
double previousB = scanner.nextDouble();
double dueTotal = getTotalDue(presentR,previousR,previousB);
Account user = new Account(id,bc,bd,customerName,customerAddress,customerNumber,periodT,periodF,presentR,previousR,previousB,dueTotal);
accountList.add(user);
break;
case 2:
case 3:
System.out.print("Enter Account Number: ");
int a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
System.out.println("Account ID: " + accountList.get(i).getId());
System.out.println("Customer Name: " +accountList.get(i).getCustomerName());
System.out.println("Customer Address: " + accountList.get(i).getCustomerAddress());
System.out.print("Customer Number: " + accountList.get(i).getCustomerNumber());
}
}
System.out.println("\nBilling Code\t\tBilling Date\t\tAmount Due");
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println(accountList.get(i).getBc()+"\t\t\t"+accountList.get(i).getBd()+"\t\t\t"+accountList.get(i).getDue());
}
}
break;
case 4:
case 5:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
}
}
break;
case 6:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
System.out.print("Enter Billing Code: ");
String b = scanner.next();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
if(b.equals(accountList.get(i).getBc())){
accountList.remove(i);
System.out.print("\nAccount Removed\n");
}else{
System.out.print("Invalid Billing Code\n");
}
}else if(a != accountList.get(i).getId()){
System.out.print("Invalid Account Number or Number not in the database.\n");
}else{
System.out.print("Try Again\n");
}
}
break;
case 7:
System.out.println("Account ID\t\tBilling Code\t\tAccount Name\t\tTotal Due\t\tPresent R\t\tPrevious R");
Collections.sort(accountList,Collections.reverseOrder());
for(int i=0; i<accountList.size();i++){
System.out.println(accountList.get(i).getId() + "\t\t\t"+accountList.get(i).getBc()+ "\t\t\t"+accountList.get(i).getCustomerName()+ "\t\t\t"+accountList.get(i).getDue()+"\t\t\t"+accountList.get(i).getPresentR()+ "\t\t\t"+accountList.get(i).getPreviousR());
}
break;
}
}while(user_choice!=8);
}
I'm new to programming in Java and I'm still learning towards it. I'm making my billing system which calcualtes the payment. My problem for this is how can I change or update the value which is already in the arraylist, I've tried the set() but I cannot make it work. using arraylist is a big jump for me and I haven't yet got a hang of it. I've watched youtube vids but they seem to show non user input arry lists
Any help?
[1]: https://i.stack.imgur.com/HhF33.png
There are two ways to do it.
First Option is Loop the list and reach the object you want to change, update its attributes. Since the object is accessed by reference, whatever values you will change it will effect.
Second option is remove the object at that index, create a new object and insert at that position.
public void testArrayList ()
{
class MyData
{
String Id = "";
String Name = "";
public MyData () {}
public MyData (String id, String name) {
Id= id;
Name = name;
}
public String toString ()
{
return " Id=" + Id + " Name=" + Name;
}
}
ArrayList myDList = new ArrayList ();
myDList.add(new MyData("1", "John"));
myDList.add(new MyData("2", "Mike"));
myDList.add(new MyData("3", "Tom"));
System.err.println ("Org List " + myDList);
MyData tmp = (MyData) myDList.get(1);
tmp.Id = "22";
tmp.Name = tmp.Name + " Changed";
System.err.println ("Mod List (Observe second Object ) " + myDList);
}
You need to set the value in ArrayList to be an object of type Account.
1.You need to get an object of type Account and use settter method to update bcode
2. Set that Account object back to ArrayList
Code TL:DR. Do you have a set method in your Account class?
//set method example
public void setBc(String newBc){ //can also use other data types as parameters
this.bc = newBc;
}
If so you can just
accountList.get(i).setBc("This New BCODE"); //The parameter can also be a variable of string type
Your code:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
If you want to update billing code in an account then get the account object and update the user entered bCode on the object. Also, you don't have to put the account back in the list:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
Account existing = accountList.get(i);
//create new account with same data except bCode
Account updated = new Account(existing.getId(),bCode, existing.getBd(),/*do same for rest of the fields */);
int index = accountList.indexOf(existing);
accountList.set(index, updated);
You have to change this part in Your program
…
Billing billing = accountList.get(i);
//String c = billing.getBc(); // this is the part in which I am having a hard time to fix, I've used
// the set but still I cannot change the element inside.
billing.setBc( yourNewBc );
//int index = accountList.indexOf(c);
//accountList.set(index, billing);
…
class names are capitalized in Java
Here in this example we have iterated over the list and modified the values of the object.
Please make a setter to the values you want to modify and follow something like this.
public class Arr {
public static void main(String args[]){
ArrayList<Person> array = new ArrayList();
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("1.add 2. modify 3.view list ; anything else to to quit");
int choice = sc.nextInt();
if (choice==1){
System.out.println("Enter ID then salary");
int id = sc.nextInt();
int salary = sc.nextInt();
Person p = new Person(id,salary);
array.add(p);
System.out.println("Done");
}
else if (choice==2){
System.out.println("Enter ID");
int id = sc.nextInt();
for (int i = 0; i < array.size(); i++){
Person p = array.get(i);
if (p.getId()==id){
System.out.println("value exits. Enter salary to be modified:");
int salary = sc.nextInt();
p.setSalary(salary);
}
}
System.out.println("Done");
}
else if (choice==3){
for (int i = 0; i < array.size(); i++)
System.out.print(" " + array.get(i).getId() + " " + array.get(i).getSalary());
}
else
break;
}
}
}
public class Person {
int id;
int salary;
public Person(int id, int salary) {
this.id = id;
this.salary = salary;
}
public int getId() {
return id;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}

Having trouble with array

I am currently trying to program a array based program. We have to make a employee class then a tester main class that holds a array of five user input employee names, salaries, and performance rating. The performance rating is used to determine a supplied raise amount. I have it basically done, but when i run the program, nothing happens even though java virtual machine is running. I have looked up and down for the error, anyone can point out what i am doing wrong?
Employee Class
public class Employee
{
private String employeeName;
private int salary;
private int performanceRating;
public Employee()
{
employeeName = "";
salary = 0;
performanceRating = 0;
}
public String getEmployeeName()
{
return employeeName;
}
public int getSalary()
{
return salary;
}
public int getPerformanceRating()
{
return performanceRating;
}
}
And this is the tester main class where the error comes in somewhere
import java.util.Scanner;
public class Tester
{
public static void main(String[] args)
{
Employee[] work = new Employee[5];
Scanner scanString = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
String employeeName = "";
double salary = 0;
double performanceRating = 0;
String choice = scanString.nextLine();
while(choice.equals("yes"))
{
for(int i = 0; i < 5 ;i++)
{
System.out.println("What is the employee's name?");
employeeName = scanString.nextLine();
System.out.println("Enter Employee's salary");
salary = scanInt.nextInt();
System.out.println("Performance? 1 = excellent, 2 = good, 3 = poor");
performanceRating = scanInt.nextInt();
work[i] = new Employee();
}
for(int j = 0; j < 5; j ++)
if(work[j].getPerformanceRating() == 1)
{
salary = salary * 0.06;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 2)
{
salary = salary * 0.04;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 3)
{
salary = salary * 0.015;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating < 5)
{
salary = salary;
System.out.println("Rating is off scale. No raise for emplyee " + employeeName);
}
System.out.println("Enter more employees? type 'yes' if you want to go again");
choice = scanString.nextLine();
}
System.out.println("Done");
}
}
The program reads from System.in. If you don't enter anything, nothing will happen.
Not sure why you have 2 Scanners instead of just one.
You have while(choice.equals("yes")) except you never prompt the user to make a choice. The program does do stuff (some of which may not all work properly), but you have to give the program input. What you can do is ask the user a question before the line String choice = scanString.nextLine();.
As a side note, you could use a switch in place of the if and else if's and it might be a little easier to read and understand.

Finding the max value in an arraylist

In this program I wrote I have to print out the name of the customer who spent the most in the store. I need help searching the array list for the customer who spent the most.
package bestcustomer;
import java.util.*;
/**
*
* #author muf15
*/
public class BestCustomer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
sales.add(salesAmount);
System.out.println("Enter customers name");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales;
return name;
}
}
You should wrap these two field in a class called probably Customer and then
Use Collections.max();
Collections.max(yourCollection, customComparator);
You should consider making Customer a class, but this would find the name with your current data structures:
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales = 0;
int index = -1;
for(int i = 0; i < sales.size(); i++) {
if(sales.get(i) > maxSales) {
index = i;
maxSales = sales.get(i);
}
}
if(index == -1) {
return null; //lists are empty
}
return customers.get(index);
}
I might be a bit late..
I think that if you create a Customer class with two fields, name and sale it would be better design as mentioned by other answers.
Then in BestCustomer you could loop through the list of customer, find the highest sales and return the name.
Something like this for BestCustomer
private ArrayList<Customer> customers = new ArrayList<Customer>();
public BestCustomer(){
Scanner in = new Scanner(System.in);
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
System.out.println("Enter customers name");
String name = in.next();
customers.add(new Customer(name, salesAmount));
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer();
System.out.print(bestCustomer);
}
private double highestSale(){
double highestSale = 0;
for(Customer c: customers)
if (c.getSales() > highestSale)
highestSale = c.getSales();
return highestSale;
}
public String nameOfBestCustomer(){
for (Customer c: customers)
if(c.matchSale(highestSale()))
return c.getName();
return null;
}
}
and this is the Customer
public class Customer {
private String name;
private double sales;
public Customer(String name, double salesAmount) {
this.name = name;
sales = salesAmount;
}
public boolean matchSale(double sales){
return this.sales == sales;
}
public double getSales(){
return sales;
}
public String getName(){
return name;
}
}
I am a beginner so I am pretty sure there is a more efficient way to do it. Also I am using two getters and as far as my understanding goes it is not the better design..
In Java8, if defined Customer like mikey said
customers.stream()
.max(Comparator.comparing(Customer::getSales))
.get()
.getName()

How to add multiple user input char and int into arrays in Java

I'm having a problem with my project in Java.
Here's the situation: the user will enter a character and integer of course code subj and units with a loop and restriction that indicates that when the total unit reaches "25" it will stop adding subj and course.
For example:
course code | subject | units
------------+-----------+-------
GE 111 | education | 3
GE 112 | history | 1
and so on..
After the user has entered the codes above, it will count all units and it will print to something thanks for the help. The code is too long, here is the most important part:
int[] a = new int[6];
Scanner sc = new Scanner(System.in);
System.out.println("\nenter units");
for (int j = 0; j < 9; j++) {
a[j] = sc.nextInt();
}
System.out.println("your subjects are:\n : ");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
System.out.print("\nEnter course code:" + a);
code = br.readLine().charAt(0);
System.out.print("\nenter course description");
subj = br.readLine().charAt(0);
System.out.print("\nenter units");
units = br.readLine().charAt(0);
case 2: break;
case 3: break;
case 4: break;
}
}
Are you trying to achieve this:
Main.java
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Make one Course container list to store a set of courses
List<Course> courses = new ArrayList<Course>();
//to store sum of units, intially 0
int unitSum = 0;
Course course = null;
while(true){
//make new course
course = new Course();
System.out.println("Enter course code:");
course.setSubjectCode(sc.nextInt());//store course code
System.out.println("Enter subject name:");
course.setSubjectName(sc.next());//store subject name
System.out.println("Enter units:");
course.setUnits(sc.nextInt());//store units
courses.add(course);//add Course to container
//take sum of units
unitSum += course.getUnits();
if(unitSum>=25)//end loop if sum reached 25
break;
}
System.out.println(courses);
sc.close();
}
}
Course.java
public class Course {
private int subjectCode;
private String subjectName;
private int units;
public Course() {
}
public int getSubjectCode() {
return subjectCode;
}
public void setSubjectCode(int subjectCode) {
this.subjectCode = subjectCode;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public int getUnits() {
return units;
}
public void setUnits(int units) {
this.units = units;
}
#Override
public String toString() {
return "Course [subjectCode=" + subjectCode + ", subjectName="
+ subjectName + ", units=" + units + "]";
}
}
this may help you..
Why don't you make object of what you need to work with? Then you can have it so much easier. Make a class and constructor of whathewer you want to use as entry new Entry(data1,data2,data3) work with all of those. It will help you when you make your program more complex.
To sum up the array to get total units
int sum=0;
for(int i:yourArray){
sum+=i;
}
The problem is that you work with all of your data as individual pars try to make some connection between them. Make object and put some functions in. (sum units), (get desc) etc. - it will be easy for you then to precede.

Need to add the numbers from an object

I am writing a program that takes names, dates and numbers from a user as many times as they enter it and then adds up the numbers that were entered. If you look at the third for loop you will see where I am trying to add. I tried doing total = cust[i].amount + total; but I cannot access amount for some reason.
This is for an assignment.(I know were not supposed to post homework questions on here but I'm stumped.)The only data member Customer is to have is name
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);
}
There's no field amount in the class Customer.
There are several issues, but you should
// Use one loop...
for(int i=0; i < cnt; i++){
if(cust[i]!= null) { // <-- check for null.
cust[i].showData();
/* or
if (cust instanceof Service) {
total += ((Service)cust[i]).amount; // <-- assuming a public amount
// field in Service. This is not a good
// practice, but your question is difficult to
// answer.
}
*/
total += cust[i].getAmount(); // <-- a method.
}
}
That is add a getAmount to your interface if you want to get the amount (or, to make this code work - change the access modifier and add a public field named amount to Customer and remove the shadowing fields in your subclasses).
Or, you can learn about Collections (which I strongly recommend you do anyway) - and actually use the correct storage method - perhaps ArrayList.
This is one solution that I could come up with, where we add a getAmount method to the interface:
import java.util.Scanner;
public class home {
/**
* #param args
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 2;
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();
total = cust[i].getAmount() + total;
}
s.close();
}
}
abstract class Customer implements Functions {
protected String name;
}
import java.util.Scanner;
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 double getAmount(){
return this.amount;
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
}
import java.util.Scanner;
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public double getAmount(){
return this.payment;
}
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);
}
}
interface Functions {
public void getData();
public void showData();
public double getAmount();
}

Categories

Resources