i'm a beginner, I barely know anything, I tired to do some classes and just mess around with methods, but for some reason the method wont print, also I'm really bad with arrays :(
main class :
public class Employees {
static Employee[] array =new Employee[3];
static int i=0;
public void insertEmployee(){
Scanner keyboard=new Scanner(System.in);
System.out.println("please fill in the information :");
System.out.println("name :");
String Name=keyboard.next();
System.out.println("ID :");
long ID=keyboard.nextLong();
System.out.println("Salary :");
double Salary =keyboard.nextDouble();
Citizen s2 =new Citizen(Name);
Employee E= new Employee(ID,s2,Salary);
array[i]=E;
}
public void main(String[] args) {
Employees m1=new Employees();
for ( i=0; i<3;++i){
Employees c1=new Employees();
c1.insertEmployee();
}
System.out.println("*****");
for (i=0;i<3;++i){
array[i].print();
}
}
}
second class :
public class Employee {
private Citizen employeeInfo =new Citizen();
private long employeeID;
private double employeeSalary;
Employee(long employeeID,Citizen employeeInfo ){
this.employeeID=employeeID;
this.employeeInfo=employeeInfo;
}
Employee(long employeeID,Citizen employeeInfo, double employeeSalary){
this.employeeID=employeeID;
this.employeeInfo=employeeInfo;
this.employeeSalary=employeeSalary;
}
void print(){
if (employeeSalary==0){
employeeSalary=-1;
}
System.out.println(employeeID+"-"+employeeInfo.getCitizenName()+"-"+employeeSalary);
}
}
and last one:
public class Citizen {
private String citizenName;
private long citizenID;
public Citizen(){
}
public Citizen(String Name){
this.citizenName=Name;
}
public Citizen(String citizenName,long citizenID){
this.citizenName=citizenName;
this.citizenID=citizenID;
}
public String getCitizenName(){
return citizenName;
}
public long getCitizenID(){
return citizenID;
}
}
thank you :)
It has to be public static void main(String[] args). The static is important
Related
I'm doing this code right now and it always returns the error "non-static variable this cannot be referenced from a static context" on the part "Teacher x1 = new Teacher(); and Student y1 = new Student()". I'm confused on what I should do to make the program work. Thanks for the help!
edit: added the other classes
edit 2: The goal of this code is to have a class Person (with name, age, and gender), another class Student (with grade), and Teacher (with salary). The Student and Teacher classes must inheritance from Person class.
My code:
import java.util.*;
import java.util.Scanner;
public class Java2Technical {
public static void main(String[] args) {
System.out.println("DATABASE");
System.out.println(" ");
System.out.println("1. Teacher");
System.out.println("2. Student");
System.out.print("Choice: ");
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
System.out.println(" ");
if(choice == 1) {
Teacher x1 = new Teacher();
System.out.print("Name: ");
Scanner scan1 = new Scanner(System.in);
x1.name = scan1.nextLine();
System.out.println(" ");
System.out.print("Age: ");
Scanner scan2 = new Scanner(System.in);
x1.age = scan2.nextInt();
System.out.println(" ");
System.out.print("Gender: ");
Scanner scan3 = new Scanner(System.in);
x1.gen = scan3.next().charAt(0);
System.out.println(" ");
System.out.print("Salary: " + x1.salary);
System.out.println(" ");
}
else if(choice == 2){
Student y1 = new Student();
System.out.print("Name: ");
Scanner scan1 = new Scanner(System.in);
y1.name = scan1.nextLine();
System.out.println(" ");
System.out.print("Age: ");
Scanner scan2 = new Scanner(System.in);
y1.age = scan2.nextInt();
System.out.println(" ");
System.out.print("Gender: ");
Scanner scan3 = new Scanner(System.in);
y1.gen = scan3.next().charAt(0);
System.out.println(" ");
System.out.print("Grade: " + y1.grade);
System.out.println(" ");
}
else{
System.out.println("Invalid Input");
}
}
public class Person {
String name;
int age;
char gen;
double grade;
double salary;
}
public class Student extends Person {
public void setName(String Brand) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGen(char gend) {
this.gen = gen;
}
public void setGrade(double grade){
this.grade = grade;
}
public String getName(String name) {
return this.name;
}
public int getAge(int age) {
return this.age;
}
public char getGen(char gend) {
return this.gen;
}
public double getGrade(double grade) {
return this.grade;
}
}
public class Teacher extends Person {
public void setName(String Brand) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGen(char gen) {
this.gen = gen;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getName(String name) {
return this.name;
}
public int getAge(int age) {
return this.age;
}
public char getGen(char gen) {
return this.gen;
}
public double getSalary(double salary) {
return this.salary;
}
}
}
Your main method is static, so you are in a static context where this does not exists.
A static member or static method is associated with the class, not an instance of the class. Static members exists once per class, non-static members are unique for each instance.
If you have an inner class like you do in your example, you can only create an instance of the inner class if you already have an instance of the outer class.
public class Outer {
public class Inner { }
public static void main (String[] args) {
var outer = new Outer();
var inner = outer.new Inner(); // notice the use of the outer instance here
}
}
If you do not wish to bind every instance of the inner class to a specific instance of the outer class, and want to be able to instantiate it independently, you need to make the inner class static:
public class Outer {
public static class Inner { }
public static void main (String[] args) {
var inner = new Inner(); // works now
}
}
Note the static keyword on the inner class, it makes instantiating the outer class unecccesary.
As an aside, you do not need to explicitly use the outer class when you are already in an instance context:
public class Outer {
public class Inner { }
Inner inner;
Outer() {
var inner = new Inner(); // `this` exists, we are in an instance of the outer class and can thus instantiate the inner class because we are in the proper object context
this.inner = inner;
}
public static void main (String[] args) {
var outer = new Outer();
var inner = outer.inner; // access the outer classes field and get the instance of the inenr class that was created in the constructor of the outer class
}
}
Please also note that proper indentation makes your code much easier to read.
Task Description
I have this problem statement:
Create a class Employee with the following private member variables.
int employeeId
String employeeName
double salary
double netSalary
Include appropriate getters and setters method in Employee class. Write the following method in the Employee class:
public void calculateNetSalary(int pfpercentage) - This method should take PF percentage as argument. Deduct the PF amount from the salary and set the netSalary.
Create a Main class which has the main method which invokes the method to get the input and prints the details as shown in the sample.
Also write a method :
public static Employee getEmployeeDetails() - which gets the employee details - id, name and salary, and returns the employee object.
public static int getPFPercentage() - which gets the PF percentage and returns the same
In the main method invoke the above two methods, and then call the calculateNetSalary method in Employee class and print the output as shown below.
Sample Input 1:
Enter Id:
101
Enter Name:
Vivek
Enter salary:
20000
Enter PF percentage:
7
Sample Output 1:
Id : 101
Name : Vivek
Salary : 20000.0
Net Salary : 18600.0
What I have done
I wrote the getter & setters methods and calculateNetSalary() method in Employee.java. I am stuck in as what and how should I write in Main.java
Employee.java
public class Employee{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;
//setters
public void setEmployeeId(int employeeId){
this.employeeId=employeeId;
}
public void setEmployeeName(String employeeName){
this.employeeName=employeeName;
}
public void setSalary(double salary){
this.salary=salary;
}
public void netSalary(double netSalary){
this.netSalary=netSalary;
}
//getters
public int getEmployeeId(){
return employeeId;
}
public String getEmployeeName(){
return employeeName;
}
public double getSalary(){
return salary;
}
public double getNetSalary(){
return netSalary;
}
public void calculateNetSalary(int pfpercentage){
pfamount=salary*pfpercentage;
netSalary=salary-pfamount;
}
}
Main.java
import java.util.Scanner;
public class Main{
public staic void main(String[] args){
Scanner sc = new Scanner(System.in);
Employee emp = new Employee();
System.out.println("Enter Id:"+setEmployeeId(sc.nextInt()))
System.out.println("Enter Name:"+setEmployeeName(sc.next()));
System.out.println("Enter salary:"+setSalary(sc.nextDouble()));
System.out.println("Enter PF percentage:");
double pfpercentage = sc.nextDouble();
public static Employee getEmployeeDetails(){
}
public static int getPFPercentage(){
}
}
}
I am unable to complete Main.java as I am not sure what and how to write.
This should be your code:
public void main(String[] args){
Scanner sc = new Scanner(System.in);
Employee emp = new Employee();
emp.setEmployeeId(sc.nextInt());
emp.setEmployeeName(sc.next()) ;
emp.setSalary(sc.nextDouble());
System.out.println("Enter PF percentage:");
double pfpercentage = sc.nextDouble();
emp.calculateNetSalary(pfpercentage);
System.out.println("Salay is " + emp.getNetSalary());
}
Also please notice that you haven't defined the type of pfamount:
public void calculateNetSalary(double pfpercentage){
double pfamount=salary*pfpercentage;
netSalary=salary-pfamount;
}
You can't define another methods inside the main() method.
You can call other methods inside it (as much as you like).
You have a couple of issues in your code. Firstly looking at Employee.java, there are a couple of issues:
Your method to set netSalary is declared as public void netSalary(double netSalary), where it should rather be public void SetNetSalary(double netSalary)
The calculation in public void calculateNetSalary(int pfpercentage) looks incorrect. If you going to pass in a double (i.e. 2 to represent 2%) then you need to divide this by 100 to convert the number to percentage.
You need to declare variables if you going to use them (namelty pfamount needs to be declared as a double before you can assign something to it).
You'll probably need a public String toString() method, for printing out your employee object.
So you'll end up with something like this:
public class Employee{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;
//setters
public void setEmployeeId(int employeeId){
this.employeeId=employeeId;
}
public void setEmployeeName(String employeeName){
this.employeeName=employeeName;
}
public void setSalary(double salary){
this.salary=salary;
}
public void setNetSalary(double netSalary){
this.netSalary=netSalary;
}
//getters
public int getEmployeeId(){
return employeeId;
}
public String getEmployeeName(){
return employeeName;
}
public double getSalary(){
return salary;
}
public double getNetSalary(){
return netSalary;
}
public void calculateNetSalary(double pfpercentage) {
double pfamount = salary * (pfpercentage / 100);
netSalary = salary - pfamount;
}
#Override
public String toString() {
String output = new StringBuffer()
.append("Id: ").append(employeeId)
.append(System.lineSeparator()).append("Name: ").append(employeeName)
.append(System.lineSeparator()).append("Salary: ").append(salary)
.append(System.lineSeparator()).append("Net Salary: ").append(netSalary).toString();
return output;
}
}
The you also have a couple of issues with your Main.java:
You can't declare methods within methods.
This is not the correct way to implement java.util.Scanner ... System.out.println("Enter Id:"+setEmployeeId(sc.nextInt())). Essentially the Scanner portion needs to be separated from the System.out (remember the only thing System.out does is print out text, it does not wait for input from Scanner).
If I understand your question correctly, you need to move some of your logic out of your main method and into getEmployeeDetails() and getPFPercentage()
So you'll end up with something like this:
import java.util.Scanner;
public class EmployeeSalaryCalculation {
private Scanner scanner;
public EmployeeSalaryCalculation() {
scanner = new Scanner(System.in);
}
public Employee getEmployeeDetails() {
Employee employee = new Employee();
System.out.println("Enter Id:");
employee.setEmployeeId(scanner.nextInt());
System.out.println("Enter Name:");
employee.setEmployeeName(scanner.next());
System.out.println("Enter salary:");
employee.setSalary(scanner.nextDouble());
return employee;
}
public double getPFPercentage(){
System.out.println("Enter PF percentage:");
return scanner.nextDouble();
}
public static void main(String[] args) {
EmployeeSalaryCalculation employeeSalaryCalculation = new EmployeeSalaryCalculation();
Employee employee = employeeSalaryCalculation.getEmployeeDetails();
employee.calculateNetSalary(employeeSalaryCalculation.getPFPercentage());
System.out.println(employee.toString());
}
}
You've made a good start. However, there are a couple of syntax errors such as forgetting to end some statements with a semi-colon. Also, as far as I know, Java doesn't support nested methods, so you shouldn't have the methods getEmployeeDetails() and getPFPercentage() inside your main method. I have rearranged the code to correct that.
Other changes I made was to your Employee class, particularly the calculateNetSalary method. pfPercentage is divided by 100 before multiplication by salary. Also, the instance variable netSalary is set to be the local variable netSalary after it has been calculated using the appropriate setter method. The method netSalary has also been renamed to setNetSalary since that is more descriptive of what the method does.
I haven't made any other changes to your code other than completing the Main class according to specifications. If there's any other part of the code that needs clarification, you can leave a comment about that.
Main.java
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
Employee newEmployee = getEmployeeDetails();
double pfPercentage = getPFPercentage();
System.out.println();
System.out.println("Confirm employee details: ");
System.out.println("Id : " + newEmployee.getEmployeeId());
System.out.println("Name : " + newEmployee.getEmployeeName());
System.out.println("Salary : " + newEmployee.getSalary());
newEmployee.calculateNetSalary(pfPercentage);
System.out.println("Net Salary : " + newEmployee.getNetSalary());
}
/**
* Gets the details of a new employee from user input
* #return the new {#link Employee}
*/
public static Employee getEmployeeDetails() {
Employee employee = new Employee();
System.out.println("Enter Id: ");
employee.setEmployeeId(scanner.nextInt());
System.out.println("Enter Name: ");
employee.setEmployeeName(scanner.next());
System.out.println("Enter salary: ");
employee.setSalary(scanner.nextDouble());
return employee;
}
/**
* Gets the PF percentage from user input
* #return the PF percentage
*/
public static double getPFPercentage(){
System.out.println("Enter PF percentage:");
double pfPercentage = scanner.nextDouble();
return pfPercentage;
}
}
Employee.java
public class Employee{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;
// Setters
public void setEmployeeId(int employeeId){
this.employeeId = employeeId;
}
public void setEmployeeName(String employeeName){
this.employeeName = employeeName;
}
public void setSalary(double salary){
this.salary = salary;
}
private void setNetSalary(double netSalary){
this.netSalary = netSalary;
}
// Getters
public int getEmployeeId(){
return employeeId;
}
public String getEmployeeName(){
return employeeName;
}
public double getSalary(){
return salary;
}
public double getNetSalary(){
return netSalary;
}
public void calculateNetSalary (double pfPercentage){
double pfAmount = salary * (pfPercentage / 100);
double netSalary = salary - pfAmount;
this.setNetSalary(netSalary);
}
}
Write a class, Manager, that extends MonthlyEmployee, and has another instance variables, bonus and an instance method, setBonus. Override the pay method and update TestEmployee accordinly.
3.Write a class, TestShapes, that creates an instance of each of our shape classes and prints it.
I am trying to rewrite the toString() to print names. I use getNm() from each employee in an arraylist of object employees. Employees have the parameters (pay, nm, hoursWorked, overtimeHours)
I have bolded the code I am focused on.
public class Main {
public static void main(String[] args){
workers workerlist = new workers();
workerlist.setNumberEmployees();
workerlist.instantiateEmployees();
System.out.println(workerlist.toString());
}
}
public class Employees extends workers{
public double pay;
public String nm;
public double hours;
public double overtime;
public Employees(double pay, String nm, double hoursWorked, double overtimeHours){
}
public double getPay(){
return pay;
}
public void setPay(double pay){
}
public String getNm(){
return nm;
}
public void setNm(String nm){
}
public double getHours(){
return hours;
}
public void setHours(double hours){
}
public double getOvertime(){
return overtime;
}
public void setOvertime(double overtime){
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class workers{
public int employeenumber;
public String nm;
ArrayList<Employees> workerList = new ArrayList<Employees>();
Scanner input = new Scanner(System.in);
public void setNumberEmployees(){
System.out.println("How many employees do you have?");
employeenumber = input.nextInt();
}
public int getNumberEmployees(){
return employeenumber;
}
public void instantiateEmployees(){
for(int i=1; i<=employeenumber; i++){
workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
}
}
public String toString(){
String st = "";
for(int i=0; i<employeenumber; i++){
**st += workerList.toString();**
// ".toString() is there to test the setting of parameters, I am interested in replacing this part.
}
return st;
}
}
Expected Output [Employee 1's name, Employee 2's name,... Employee n's name]
I think below code will give your expected result.
public class Main {
public static void main(String[] args) {
workers workerlist = new workers();
workerlist.setNumberEmployees();
workerlist.instantiateEmployees();
System.out.println(workerlist.toString()); //call toString to take workerlist
}
}
Override Employees toString method and do not forget update nm parameter in constructor
public class Employees extends workers {
public double pay;
public String nm;
public double hours;
public double overtime;
public Employees(double pay, String nm, double hoursWorked, double overtimeHours) {
this.nm = nm; //do not forget set value
}
public double getPay() {
return pay;
}
public void setPay(double pay) {
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
}
public double getHours() {
return hours;
}
public void setHours(double hours) {
}
public double getOvertime() {
return overtime;
}
public void setOvertime(double overtime) {
}
#Override
public String toString() {
return getNm(); //Employees toString method will return nm
}
}
override toString method and call arraylist's toString method.
public class workers {
public int employeenumber;
public String nm;
ArrayList<Employees> workerList = new ArrayList<Employees>();
Scanner input = new Scanner(System.in);
public void setNumberEmployees() {
System.out.println("How many employees do you have?");
employeenumber = input.nextInt();
}
public int getNumberEmployees() {
return employeenumber;
}
public void instantiateEmployees() {
for (int i = 1; i <= employeenumber; i++) {
workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
}
}
public String toString() {
return workerList.toString(); //no need to iterate on arraylist, Arraylist.toString method will call each Employees toString method.
}
}
Yusuf K. and Andrew Tobilko have answered your question correctly. Just to give you some hints to improve your classes a bit:
Why do you call Employees eventhough your class can represent a single employee; so I would call it Employee instead.
Why do you define the nm field twice? It is declared in Workers class from which the Employees class is derived.
setNumberEmployees() method does not comply with JavaBeans convention; it must be declared as
public void setNumberEmployees(final String noEmployees) {
employeenumber = noEmployees;
}
And the call to setNumberEmployees() should be done in the main() method as
public static void main(String[] args){
workers workerlist = new workers();
Scanner input = new Scanner(System.in);
workerlist.setNumberEmployees(input.nextInt());
workerlist.instantiateEmployees();
System.out.println(workerlist.toString());
}
And lastly, you are speaking about parameter(s). They are actually called fields or instance variable(s).
public String toString(){
String st = "";
for(int i=0; i < employeenumber; i++)
st += workerList.get(i).toString();
return st;
}
But this solution is not the best. I suggest you the next one:
public String toString(){
StringBuilder builder = new StringBuilder();
workerList.stream().map(Employees::toString).forEach(builder::append);
return builder.toString();
}
And, of course, you have to override toString() in the Employees class. For example,
#Override public String toString() {
return new StringJoiner(", ")
.add(Double.toString(pay))
.add(nm)
.add(Double.toString(hours))
.add(Double.toString(overtime))
.toString();
}
I am following along with the Java for Dummies book and I ran into a problem. I can't figure out why #Override isn't working. I'm sure it has to do with my code because I have gotten a polymorphic array to work with override before, but it was too simple for me to mimic.
import static java.lang.System.out;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class DoPayrollTypeP {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner diskScanner = new Scanner(new File("EmpInfoNew.txt"));
Scanner kbdScanner = new Scanner (System.in);
for(int empNum = 1; empNum<=3; empNum++){
payOneFTEmployee (diskScanner);
}
for(int empNum = 4; empNum<=6; empNum++){
payOnePTEmployee(diskScanner, kbdScanner);
}
}
public static void payOneFTEmployee(Scanner diskScanner){
FullTimeEmployee ftemployee = new FullTimeEmployee();
ftemployee.setName(diskScanner.nextLine());
ftemployee.setJobTitle(diskScanner.nextLine());
ftemployee.setWeeklySalary(diskScanner.nextDouble());
ftemployee.setBenefitDeduction(diskScanner.nextDouble());
diskScanner.nextLine();
diskScanner.nextLine();
ftemployee.cutCheck(ftemployee.findPaymentAmount());
out.println();
}
public static void payOnePTEmployee(Scanner diskScanner, Scanner kbdScanner) {
PartTimeEmployee ptemployee = new PartTimeEmployee();
ptemployee.setName(diskScanner.nextLine());
ptemployee.setJobTitle(diskScanner.nextLine());
ptemployee.setHourlyRate(diskScanner.nextDouble());
diskScanner.nextLine();
diskScanner.nextLine(); //Reads the dashed line that
// separates two employees
out.print("Enter ");
out.print(ptemployee.getName());
out.print("'s hours worked this week: ");
int hours = kbdScanner.nextInt();
ptemployee.cutCheck(ptemployee.findPaymentAmount(hours));
out.println();
}
}
Next class:
import static java.lang.System.out;
public class Employee {
private String name;
private String jobTitle;
public void setName(String nameIn) {
name = nameIn;
}
public String getName() {
return name;
}
public void setJobTitle(String jobTitleIn) {
jobTitle = jobTitleIn;
}
public String getJobTitle() {
return jobTitle;
}
public void cutCheck(double amountPaid){
out.printf("Pay to the order of %s", name);
out.printf("(%s) ***$", jobTitle);
out.printf("%,.2f\n", amountPaid);
}
}
Next Class:
public class PartTimeEmployee extends Employee{
private double hourlyRate;
public void setHourlyRate(double hourlyRateIn) {
hourlyRate = hourlyRateIn;
}
public double getHourlyRate() {
return hourlyRate;
}
public double findPaymentAmount(int hours){
return hourlyRate * hours;
} //method that should be overriden
}
Class That should override:
public class PartTimeWithOver extends PartTimeEmployee{
#Override
public double findPaymentAmount(int hours) {
if(hours <= 40) {
return getHourlyRate() * hours;
} else {
return getHourlyRate() * 40 +
getHourlyRate() * 2 * (hours - 40);
}
}
}
EmpInfoNew.(txt) file
jo shmo
Ceo
5000.00
500.00
edd shmoe
Captain
5000.00
500.00
bob shmo
Honorary Exec
1000.00
200.00
Dave shmo
driver
7.25
edd blah
Cook
8.50
len shmo
Head of Kitchen
12.50
You have instantiated object as
PartTimeEmployee ptemployee = new PartTimeEmployee();
It is a base class of PartTimeWithOther so it cannot call overridden method in derived class.
Change to
PartTimeEmployee ptemployee = new PartTimeWithOver();
Here is an nice tutorial with diagrams that explains Polymorphism
You never use PartTimeWithOver, you only work with PartTimeEmployee.
So your overriden method is never called.
I am trying to create mutliple objects of a type of class I made. I then want to transfer these values into the array list. How can I create objects using a while loop that have different names. For example here is my code now, but it would only make an object of one name.
Customer cust = new Customer("bob", 20.0);
and my constructor if you want to see:
public Customer(String customerName, double amount)
{
String name=customerName;
double sale=amount;
}
StoreTest class (with main method):
import java.util.ArrayList;
import java.util.Scanner;
public class StoreTest {
ArrayList<Customer> store = new ArrayList<Customer>();
public static void main (String[] args)
{
double sale=1.0; //so the loop goes the first time
//switch to dowhile
Scanner input = new Scanner(System.in);
System.out.println("If at anytime you wish to exit" +
", please press 0 when asked to give " +
"sale amount.");
while(sale!=0)
{
System.out.println("Please enter the " +
"customer's name.");
String theirName = input.nextLine();
System.out.println("Please enter the " +
"the amount of the sale.");
double theirSale = input.nextDouble();
store.addSale(theirName, theirSale);
}
store.nameOfBestCustomer();
}
}
Customer class:
public class Customer {
private String name;
private double sale;
public Customer()
{
}
public Customer(String customerName, double amount)
{
name=customerName;
sale=amount;
}
}
Store class (has methods for messing with arraylist:
import java.util.ArrayList;
public class Store {
//creates Customer object and adds it to the array list
public void addSale(String customerName, double amount)
{
this.add(new Customer(customerName, amount));
}
//displays name of the customer with the highest sale
public String nameOfBestCustomer()
{
for(int i=0; i<this.size(); i++)
{
}
}
}
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer class has variables called name and sale, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}