我正在练习动态编程,我通过创建银行项目来做到这一点。在这里,我想有很多客户,每个客户中的每一个都可以拥有许多不同容量的礼品卡。因此,我在类客户中创建了一个class giftCard1,但是如何实例化并添加它。这样,当我迭代该客户时,我就可以获取礼品卡细节。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
class Customer
{
int id;
String pwd;
int gift;
int pin;
int bal=0;
//int giftcard balance
class giftcard1
{
int gift_bal;
List<String> l2=new ArrayList<String>();
}
}
class MyClass
{
public static void main(String args[])
{
Scanner sc=new Scanner((System.in));
List<Customer> l1=new ArrayList<Customer>();
int choice=1;
while(choice==1||choice==2)
{
System.out.println("1.Account Creation 2.Purchase");
choice=sc.nextInt();
cancel:
for(int j=0;j<1;j++) {
if (choice == 1) {
System.out.println("Please enter id and pwd");
int id1 = sc.nextInt();
String s = sc.next();
char c[] = s.toCharArray();
int i;
for (i = 0; i < s.length(); i++) {
c[i] = (char) (c[i] + 1);
//System.out.print(c[i]);
}
String s1 = new String(c);
System.out.println(s1);
Customer cu = new Customer();
Customer.giftcard1 g=new cu.giftcard1();
//need help above
cu.id = id1;
cu.pwd = s1;
l1.add(cu);
System.out.println("1.GiftCCard 2.TopUP 3. Transaction History 4.Block 5.Logout");
int ch1 = sc.nextInt();
while ((ch1!=0)) {
if (ch1 == 1) {
int giftcard = (int) (Math.random() * 100000);
int pin = (int) (Math.random() * 10000);
cu.gift = giftcard;
cu.pin = pin;
System.out.println("Giftcard No " + giftcard + " " + "Pin " + pin);
}
if (ch1 == 2) {
System.out.println("Enter the amount needed to Recharge");
int amt = sc.nextInt();
if(amt>cu.bal)
{
System.out.println("Not enough Money");
}
else
{
g.gift_bal=amt;
g.l2.add(amt+" is added");
}
}
}
}
}
}
}
}
我想为客户对象创建一个类礼品卡的对象g。
首先,我建议学习命名约定。
第二我也建议将GiftCard
-CLASS移出Customer
-Class。
要存储n
GiftCard
S,您应该将List<GiftCard>
添加到Customer
-CLASS作为类成员。
class Customer {
int id;
String pwd;
int gift;
int pin;
int bal=0;
List<GiftCard> giftCards;
}
class GiftCard {
int balance;
}
注意您应该检查如何与构造函数一起使用。
因此您创建并存储它:
Customer customer = ...;
....
customer.giftCards = new ArrayList<>();
GiftCard card1 = new GiftCard();
card1.balance = 100;
customer.giftCards.add(card1);
现在,客户有1个 GiftCard
, balance
100
这是示例:
Customer c = ...
Customer.giftcard1 g = c.new giftcard1();
您必须通过添加public
修改器来使两个类别可见。