gpt4 book ai didi

java - 如何向对象类添加信息?

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:02 24 4
gpt4 key购买 nike

class Client{
String name;

Client(String name){
this.name=name;
}

Client (){
name=null;
}
}

class Cashier{

LinkedList <Client> cashierclients;


Cashier(LinkedList<Client> cashierclients){
this.cashierclients=cashierclients;
}
Cashier(){
//this.cashierclients=null;
}

}
class test{
public static void main(String args []){

LinkedList<Client> l=new LinkedList<Client>();

//i do some scans here to add the names of persons to the LinkedList l

Cashier [] cashier=new Cashier[numberofcashiers];

for(int i=0;i<numberofcashiers; i++){
cashier[i]=new Cashier();
}

现在我想向收银员添加一个客户[0],我这样做:

cashier[0].cashierclients.addLast(l.get(0));

一切正常,但是当我想打印出纳员[1]的大小时,它返回1,但它应该返回0,因为我没有向出纳员[1]添加任何人。关于哪里出了问题有什么想法吗?

// the error happens here
cashier[1].cashierclients.size();

最佳答案

程序现在正在运行,它显示 cashier[1] 大小中的错误,应返回 0 而不是 1

import java.util.*;
class Client {
String name;

Client(String name) {
this.name = name;
}

Client() {
name = null;
}
}

class Cashier {

LinkedList<Client> cashierclients;


Cashier(LinkedList<Client> cashierclients) {
this.cashierclients = cashierclients;
}

Cashier() {
//this.cashierclients=null;
}

}

public class test {
public static void main(String args[]) {

LinkedList<Client> l = new LinkedList<Client>();

// i created this LinkedList to solve the nullpointerexception error

LinkedList<Client> empty =new LinkedList<Client>();

Client client1=new Client("Person1");
l.addLast(client1);

Cashier[] cashier = new Cashier[10];

for (int i = 0; i < 10; i++) {
cashier[i] = new Cashier();
}

// i did this to solve the nullpointerexception error

for(int i=0; i<10; i++){
cashier[i].cashierclients=empty;
}

cashier[0].cashierclients.addLast(l.get(0));

System.out.println(cashier[1].cashierclients.size());
//this should return zero
System.out.println(cashier[1].cashierclients.size());

}
}

关于java - 如何向对象类添加信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30114864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com