【发布时间】:2013-11-26 12:43:32
【问题描述】:
我正在尝试创建我制作的一类类型的多个对象。然后我想将这些值传输到数组列表中。如何使用具有不同名称的 while 循环创建对象。例如,这是我现在的代码,但它只会生成一个名称的对象。
Customer cust = new Customer("bob", 20.0);
如果你想看看我的构造函数:
public Customer(String customerName, double amount)
{
String name=customerName;
double sale=amount;
}
StoreTest 类(带有 main 方法):
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();
}
}
客户类别:
public class Customer {
private String name;
private double sale;
public Customer()
{
}
public Customer(String customerName, double amount)
{
name=customerName;
sale=amount;
}
}
Store 类(有处理数组列表的方法:
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++)
{
}
}
}
【问题讨论】:
-
你的构造函数没有对传递的参数做任何有用的事情。
-
创建一个包含名称的字符串数组,当您循环添加对象时,在该数组中选择一个随机值。
-
什么意思?不是在创建 Customer 对象吗?
-
可以,但不设置任何字段,只设置局部变量。
-
我还有其他方法可以访问局部变量。
标签: java object arraylist while-loop