I have two classes:
Products:
01; Desinfectante
02; Aerosol
03; Limpia Vidrio
04; Desengrasante
05; Mata mosquitos
06; Mata cucarachas
07; Aceite en aerosol
Instructions:
01;1;Elevar la masa hasta llegar a tal punto;0;10
01;1;Mezclar este material con anterior;1;15
01;2;Relevar;2;5
01;3;Llevar;00;0
02;1;Descripcion;7;2
02;2;Descripcion;6;2
02;2;Descripcion;00;0
03;1;Descripcion;1;1
03;1;Descripcion;2;9
03;2;Descripcion;00;0
03;3;Descripcion;5;2
03;4;Descripcion;6;2
03;4;Descripcion;3;10
04;1;Descripcion;00;0
04;2;Descripcion;1;2
04;3;Descripcion;1;0
04;3;Descripcion;2;2
04;3;Descripcion;3;2
04;4;Descripcion;7;1
04;4;Descripcion;6;2
05;1;Descripcion;7;20
05;1;Descripcion;6;9
05;2;Descripcion;00;0
05;3;Descripcion;1;2
05;3;Descripcion;2;10
06;1;Descripcion;2;12
06;1;Descripcion;4;1
06;1;Descripcion;6;8
06;2;Descripcion;5;4
06;2;Descripcion;7;2
07;1;Descripcion;1;12
07;1;Descripcion;2;2
07;2;Descripcion;3;19
07;2;Descripcion;4;4
07;2;Descripcion;00;2
07;2;Descripcion;5;12
The thing is this: i have to insert the instructions ArrayList into the Products. The link between them is the first number, that is the code of the product.
I tried two things, the first one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
products.get(i).getInstr().get(n).setCodProd(instructions.get(j).getCodProd());
products.get(i).getInstr().get(n).setDescr(instructions.get(j).getDescr());
products.get(i).getInstr().get(n).setMat(instructions.get(j).getMat());
products.get(i).getInstr().get(n).setMatNec(instructions.get(j).getMatNec());
n++;
}
}
n = 0;
}
The second one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).setInstr(instructions);
n++;
}
}
n = 0;
}
return products;
}
You are getting NullPointerException because of
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
You are not checking whether the list products.get(i).getInstr() has elements or not. When the list is empty and when you are accessing it as products.get(i).getInstr().get(0) it's throwing you NullPointerException because trying to get the first element of an empty list. So before you do this operation, make sure that products.get(i).getInstr() is not empty.
If they are of same type, you can directly add the whole arraylist :
products.get(i).getInstr().addAll(instructions); // again make sure that is not empty.
If you just want to replac, use :
products.get(i).setInstr(instructions.get(j));
Products Class
package productsandinstructions;
import java.util.List;
public class Product {
private int productId;
private String productName;
private List instructions;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
}
Instruction Class
package productsandinstructions;
public class Instruction {
private int productId;
private int instructionId;
private String instDesc;
private int mat;
private int matNec;
private boolean done;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getInstructionId() {
return instructionId;
}
public void setInstructionId(int instructionId) {
this.instructionId = instructionId;
}
public String getInstDesc() {
return instDesc;
}
public void setInstDesc(String instDesc) {
this.instDesc = instDesc;
}
public int getMat() {
return mat;
}
public void setMat(int mat) {
this.mat = mat;
}
public int getMatNec() {
return matNec;
}
public void setMatNec(int matNec) {
this.matNec = matNec;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
Main Class
package productsandinstructions;
import java.util.List;
public class ProductsAndInstructionsMain {
private List products;
private List instructions;
public List getProducts() {
return products;
}
public void setProducts(List products) {
this.products = products;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
public static void main(String[] args) {
ProductsAndInstructionsMain main = new ProductsAndInstructionsMain();
main.mergeProductsAndInstructions();
}
public void mergeProductsAndInstructions() {
for (Product product : products) {
for (Instruction instruction : instructions) {
if ((!(instruction.isDone())) && (instruction.getProductId() == product.getProductId())) {
product.getInstructions().add(instruction);
instruction.setDone(true);
}
}
}
}
}
Related
I'm learning java. I have trouble about arraylist in my java program. How can I remove a room in arraylist in Room and count the number of rooms has the size smaller than 40. I just coded 2 methods which were removeRoom and countRoomBySize in class MyRoom. My code has error in Net Beans. Anyone help me to check this code, please. Thank so much. Here is my code
My Main class
public class MyMain {
public static void main(String[] args) {
//create a list of rooms
MyRoom m = new MyRoom();
m.addRoom(new Room("HB201L",35));
m.addRoom(new Room("HB401R",45));
m.addRoom(new Room("211",30));
m.sort();
m.list();
//1.
m.removeRoom("211");
m.list();
//2.
int c = m.countRoomBySize(40);
System.out.println(c);//2
}
}
Class Room
public class Room implements Comparable<Room> {
#Override
public int compareTo(Room o) {
return o.name.compareToIgnoreCase(this.name);
}
//instanced variables
private int size;
private String name;
public Room() {
name = "";
size = 0;
}
public Room(String name, int size) {
this.name = name;
this.size = size;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Class MyRoom
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MyRoom implements IRoom {
List<Room> rooms;
public MyRoom() {
rooms = new ArrayList();
}
#Override
public void addRoom(Room r) {
//append r to the end of list rooms
rooms.add(r);
}
#Override
public void list() {
for (int i = 0; i < rooms.size(); i++) {
Room r = rooms.get(i);
System.out.printf("%-20s%-10d\n",r.getName(),r.getSize());
}
}
#Override
public void removeRoom(){
for (int i = 0; i < rooms.size(); i++) {
if(rooms.get(i).getName() == "211")
rooms.remove(rooms);
}
}
#Override
public int countRoomBySize(){
int s,i,n;
n = rooms.size();
s = 0;
for(i=0;i<n;i++) {
if(rooms.get(i).getSize() > 40)
s++;
}
return(s);
}
public void sort() {
Collections.sort(rooms);
}
}
Interface IRoom
public interface IRoom {
//only contain public members: constants and method declaration
public final int MAX = 10;
public void addRoom(Room r);
public void list();
public void removeRoom();
public int countRoomBySize();
}
interface A {
void f();
}
interface B extends A {
void g();
}
interface C {}
First change your interface IRoom like this :
public void removeRoom(String name);
public int countRoomBySize(int size);
In the MyRoom class change removeRoom method like this :
#Override
public void removeRoom(String name){
for (int i = 0; i < rooms.size(); i++) {
if(name.equalsIgnoreCase(rooms.get(i).getName())){
rooms.removeIf(r -> r.getName().equals(name));
System.out.println("Removed !");
}
}
}
And the countRoomBySize method like this :
#Override
public int countRoomBySize( int size){
int s,i,n;
n = rooms.size();
s = 0;
for(i=0;i<n;i++) {
if(rooms.get(i).getSize() > size)
s++;
}
return(s);
}
Best of luck !
removeRoom can be shortened to: rooms.remove(rooms.indexOf("211")) or perhaps even rooms.remove("211");
Nice that you are starting to learn java.
The simplest solution here is to put your room in an Hashmap and store the room number as key;
public class MyMain {
public static void main(String[] args) {
Hashmap<String,Room> rooms = new Hashmap();
rooms.add("211",new Room("HB201L",35);
rooms.add("HB401R",new Room("HB401R",45);
rooms.remove("211");
int size = rooms.size();
int smallRooms = calculateSmallRooms(rooms.values(),30);
}
private int calculateSmallRooms(Collection<Room> rooms, int minimalSize) {
int smallRooms = 0;
for(Room room: rooms) {
if (room.size < minimalSize) {
smallRooms++;
}
return smallRooms;
}
I have a Navigation class where I am dynamically creating the navigation I am having two tables folder(it is directory that contains files) and content(it is like files or pages that will render the content on the public site). I have created a Navigation class in which I am having a wrapper class for merging the fields of content into the folder. I have tried using #OrderBy and #OrderColumn but I came to know that it will only work with collections.
List<Folder> folder = folderRepository.findAllByNavDepthLessThanOrderByNavDepthAsc(3);
here I am sorting it with navDepth(this column belongs to Folder entity) I also want to sort it with navOrder(this column belongs to Content entity)
#Service
public class NavigationService {
#Qualifier("jdbcMySQL")
private JdbcTemplate jdbcTemplate;
private FolderRepository folderRepository;
private FolderService folderService;
#Autowired
public NavigationService(JdbcTemplate jdbcTemplate,
FolderRepository folderRepository,
FolderService folderService) {
this.jdbcTemplate = jdbcTemplate;
this.folderRepository = folderRepository;
this.folderService = folderService;
}
#Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public Map<String, NavigationItem> navigationItems() {
// TODO: // CROSS cutting AOP springs
// TODO: http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#aop
List<Folder> folder = folderRepository.findAllByNavDepthLessThanOrderByNavDepthAsc(3);
// List<Folder> folder = folderService.navigation();
Map<String, NavigationItem> navItems = new LinkedHashMap<String, NavigationService.NavigationItem>();
for (int i = 0; i < folder.size(); i++) {
NavigationItem ni = new NavigationItem();
ni.setNavDepth((int) (folder.get(i).getNavDepth()));
ni.setFileNamePath(folder.get(i).getDirectoryPath());
ni.setFilepath(folder.get(i).getDirectoryPath());
ni.setChildren(folder.get(i).getContent());
for (int k = 0; k < folder.size(); k++) {
if(folder.get(i).getId() == folder.get(k).getParentId()) {
ni.addSubFolder(folder.get(k));
System.out.println(folder.get(i).getTitle());
System.out.println(folder.get(k));
System.out.println("---!!!!!!________----------!!!!!!!!");
}
}
navItems.put(folder.get(i).getTitle(), ni);
}
return navItems;
}
public class NavigationItem {
private long id;
private long parentId;
private String title;
private String fileName;
private String fileNamePath;
private int navDepth;
private int navOrder;
private String parentFileName;
private String filePath;
private String folderName;
#OrderColumn(name="navOrder ASC")
private List<Content> children = new ArrayList();
private ArrayList<Folder> subFolder = new ArrayList();
public void setSubFolder(ArrayList<Folder> subFolder) {
this.subFolder = subFolder;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public ArrayList<Folder> getSubFolder() {
return subFolder;
}
public void addSubFolder(Folder subFolder) {
this.subFolder.add(subFolder);
}
public void setChildren(List<Content> list) {
this.children = list;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileNamePath() {
return fileNamePath;
}
public void setFileNamePath(String fileNamePath) {
this.fileNamePath = fileNamePath;
}
public long getNavDepth() {
return navDepth;
}
public void setNavDepth(int navDepth) {
this.navDepth = navDepth;
}
public long getNavOrder() {
return navOrder;
}
public void setNavOrder(int navOrder) {
this.navOrder = navOrder;
}
public String getParentFileName() {
return parentFileName;
}
public void setParentFileName(String parentFileName) {
this.parentFileName = parentFileName;
}
public List<Content> getChildren() {
return children;
}
public void addChild(Content child) {
children.add(child);
}
public String getFilepath() {
return filePath;
}
public void setFilepath(String filePath) {
this.filePath = filePath;
}
}
}
Use a Comparator<NavigationItem> and pass that to Collections.sort() or similar methods.
The comparator might look like this:
class NavComparator implements Comparator<NavigationItem> {
int specialValueNoChildren = -1; //assuming nav_order is always 0 or greater
int compare(NavigationItem o1, NavigationItem o2) {
int max1 = getMaxNavOrder( o1 );
int max2 = getMaxNavOrder( o2 );
return Integer.compare( max1, max2 );
}
int getMaxNavOrder( NavigationItem ni ) {
int max = specialValueNoChildren;
for( Content child : ni.getChildren() ) {
max = Math.max(max, child.getNavOrder());
}
return max;
}
}
Here the maximum nav order of all children is selected with -1 being the special case of no children. Then the items are compared by their respective children's maximum nav order.
If you need a different order change that accordingly, e.g. by reversing max1 and max2 or by getting the lowest nav order of the children etc.
I have an arrayList with following values:
static ArrayList<DTONodeDetail> tree;
public static void main(String[] args) {
// TODO Auto-generated method stub
tree=new ArrayList<DTONodeDetail>();
//first argument->NodeId
//second->NodeName
// third -> ParentNodeId
tree.add(getDTO(1,"Root",0));
tree.add(getDTO(239,"Node-1",1));
tree.add(getDTO(242,"Node-2",239));
tree.add(getDTO(243,"Node-3",239));
tree.add(getDTO(244,"Node-4",242));
tree.add(getDTO(245,"Node-5",243));
displayTree(tree.get(0));
}
public static DTONodeDetail getDTO(int nodeId,String nodeName,int parentID)
{
DTONodeDetail dto=new DTONodeDetail();
dto.setNodeId(nodeId);
dto.setNodeDisplayName(nodeName);
dto.setParentID(parentID);
return dto;
}
Now i want to display above data in tree structure as below using simple java code:
Root
-----Node-1
------------Node-2
------------------Node-4
------------Node-3
------------------Node-5
I have tried following but unable to get desire result:
public static void displayTree(DTONodeDetail dto){
ArrayList<DTONodeDetail> childs = selectChild(dto.getNodeId());
System.out.println(dto.getNodeDisplayName());
for(DTONodeDetail obj:childs){
displayTree(obj);
}
}
public static ArrayList<DTOWorkSpaceNodeDetail> selectChild(int nodeID){
ArrayList<DTOWorkSpaceNodeDetail> list=new ArrayList<DTOWorkSpaceNodeDetail>();
for(int i=0;i<tree.size();i++)
{
if(tree.get(i).getParentID()==nodeID){
list.add(tree.get(i));
}
}
return list;
}
Please Provide some guide or code.
You should do like this
static void displayTree(DTONodeDetail root ,int level){
System.out.print(prefix(level));
System.out.println(root.name);
ArrayList<DTONodeDetail> children = selectChild(dto.getNodeId());
for(DTONodeDetail child : children){
displayTree(child, level + 1);
}
}
the prefix is a func to build enough '----'
static String prefix(int level){
StringBuilder s = new StringBuilder();
for(int i = 0; i < level; i++){
s.append("----");
}
return s.toString();
}
Result
displayTree(node1, 0);
Node-1
----Node-2
--------Node-4
----Node-3
--------Node-5
The only problem with your implementation that I see, is that the output is as expected, but flat (i.e. no ---- at the beginning of child lines). This is because displayTree() currently has no way of knowing at which level the node it is printing is.
I propose this:
public static void displayTree(DTONodeDetail dto, int charsBeforeNodename){
ArrayList<DTONodeDetail> childs = selectChild(dto.getNodeId());
for(int i = 0; i <= charsBeforeNodename; i++){
System.out.println("-");
}
System.out.println(dto.getNodeDisplayName());
for(DTONodeDetail obj:childs){
displayTree(obj, charsBeforeNodename + dto.getNodeDisplayName().length());
}
}
Sorry, I misunderstood the question.
I updated them.
public class DTONodeDetail {
private int nodeId;
private String nodeName;
private int parentId;
public DTONodeDetail() {
}
public DTONodeDetail(int nodeId, String nodeName, int parentId) {
this.nodeId = nodeId;
this.nodeName = nodeName;
this.parentId = parentId;
}
public int getNodeId() {
return nodeId;
}
public void setNodeId(int nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
private static List<DTONodeDetail> tree;
public static DTONodeDetail getDTO(int nodeId, String nodeName, int parentID) {
DTONodeDetail dto = new DTONodeDetail();
dto.setNodeId(nodeId);
dto.setNodeName(nodeName);
dto.setParentId(parentID);
return dto;
}
private static List<DTONodeDetail> selectChildren(int parentId) {
List<DTONodeDetail> result = new ArrayList<DTONodeDetail>();
for (DTONodeDetail d : tree) {
if (d.getParentId() == parentId) {
result.add(d);
}
}
return result;
}
public static void displayTree(DTONodeDetail dto, int level) {
List<DTONodeDetail> childs = selectChildren(dto.getNodeId());
String space = "";
for (int i = 0; i < level; i++) {
space += "\t";
}
System.out.println(space + dto.getNodeName());
if(childs.size()>0){
level ++;
}
for (DTONodeDetail obj : childs) {
displayTree(obj, level);
}
}
public static void main(String[] args) {
tree = new ArrayList<DTONodeDetail>();
tree.add(getDTO(1, "Root", 0));
tree.add(getDTO(239, "Node_1", 1));
tree.add(getDTO(242, "Node_2", 239));
tree.add(getDTO(243, "Node_3", 239));
tree.add(getDTO(244, "Node_4", 242));
tree.add(getDTO(245, "Node_5", 243));
displayTree(tree.get(0), 0);
}
}
Result:
Root
Node_1
Node_2
Node_4
Node_3
Node_5
Basically I have multiple classes and I'm trying to get an array of LineItem for each Item that a customer purchases. LineItem includes the UPC, Description, Price, Quantity, SubTotal and Discount which is all stored in a seperate class. I'm trying to get it that when you use the method addItemToSaleList it will add to the array. I need to use an array and not an array list, so I have to copy over the array to a temp array, and then recreate a new array adding to the number the array can store and then recopying it over. I'm stuck getting the array to generate. Below is the code I have
public class Product {
private double price;
private String description;
private String ProductCode;
private DiscountStrategy discoutStrategy;
public Product(double price, String description, String ProductCode, DiscountStrategy discoutStrategy) {
this.price = price;
this.description = description;
this.ProductCode = ProductCode;
this.discoutStrategy = discoutStrategy;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProductCode() {
return ProductCode;
}
public void setProductCode(String ProductCode) {
this.ProductCode = ProductCode;
}
public DiscountStrategy getDiscountStrategy() {
return discoutStrategy;
}
public void setDiscoutStrategy(DiscountStrategy discoutStrategy) {
this.discoutStrategy = discoutStrategy;
}
}
public class LineItem {
private Product product;
private double quantity;
public LineItem(Product product, double quantity) {
this.product = product;
this.quantity = quantity;
}
//Calculates the Discount Amount whether or not it's a percentage or dollar
//off
public double getDiscountAmount () {
return product.getDiscountStrategy().getDiscount(product.getPrice(), quantity);
}
//Calculates the Subtotal, gets the quantity from the DiscountStrategy and then
//the price from the product
public double getSubTotal() {
return quantity * product.getPrice();
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public class Receipt {
private LineItem[] lineItem = new LineItem[0];
public Receipt(LineItem[] lineItem) {
this.lineItem = lineItem;
}
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = new LineItem[tempItemList.length];
for (int j = 0; j < lineItem.length; j++) {
lineItem[j] = tempItemList[j];
}
}
public LineItem[] getLineItem() {
return lineItem;
}
I would remove addItemToSaleList() and implement addProductToTotalSale(LineItem) like so
public void addProductToTotalSale(LineItem li) {
// Allocate the memory.
LineItem[] tempLineItem = new LineItem[1 + lineItem.length];
// Copy the array.
if (lineItem.length > 0) {
System.arraycopy(lineItem, 0, tempLineItem, 0, lineItem.length);
}
// add the new item to the new slot.
tempLineItem[lineItem.length] = li;
// update the internal array reference.
lineItem = tempLineItem;
}
Next, you should protect your constructor from null;
public Receipt(LineItem[] lineItem) {
// Try and protect from bad calls, removes need to check for nulls in
// add (addProductToTotalSale) routine.
if (lineItem != null) {
this.lineItem = lineItem;
}
}
Because you provide a default 0 sized array your code appears to be safe to continue to include the default constructor. But, you might consider making your Receipt class immutable.
I'm not sure why you are making two new arrays. You only need one...
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
lineItem[lineItem.length-1] = li;
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = tempItemList;
}
I am working on an exercise where i build a bank system, I created an account class, a client class and a bank class, however when I check the program I get:
Exception in thread "main" java.lang.NullPointerException.
Here are my classes:
package bank.elements;
public class Account {
private int id;
private float balance;
//constructors
public Account(int id, float balance){
this.setId(id);
this.setBalance(balance);
}
public Account (int id){
this.id=id;
this.setBalance(0);
}
//getters
public int getId(){
return this.id;
}
public float getBalance(){
return this.balance;
}
//setters
public void setBalance(float balance){
this.balance+=balance;
}
public void setId(int id){
this.id=id;
}
}
package bank.elements;
public class Client {
private int id;
private String name;
private String rank;
private float balance;
private Account[] accounts = new Account[100];
public Client(){
}
//getters
public int getId(){
return id;
}
public String getName(){
return name;
}
public String getRank(){
return rank;
}
public float getBalance(){
return balance;
}
public float getAccountBalance(int id){
float balance = 0;
for (int i = 0; i < accounts.length; i++) {
if(accounts[i].getId()==id){
balance = accounts[i].getBalance();
}
}
return balance;
}
public float getFortune(){
float sum = 0;
for (int i = 0; i < accounts.length; i++) {
sum+=getAccountBalance(i);
}
sum+=getBalance();
return sum;
}
//setters
public void setName(String name){
this.name = name;
}
public void setBalance(float balance){
this.balance+=balance;
}
public void setId(int id){
this.id=id;
}
public void addAccount(int id){
for (int i = 0; i < accounts.length; i++) {
if(accounts[i]==null){
accounts[i].setId(id);
}
}
}
}
package bank.elements;
public class Bank {
public Bank(){
}
public Client[] clients = new Client[100];
public float getBalance(){
float sum = 0;
for (int i = 0; i < clients.length; i++) {
sum+= clients[i].getFortune();
}
return sum;
}
public void addClient(){
for (int i = 0; i < clients.length; i++) {
if(clients[i] == null){
clients[i].setId(i);
}
}
}
public void removeClient(int id){
for (int i = 0; i < clients.length; i++) {
if(clients[i].getId()==id){
clients[i]=null;
for (int j = (i+1); j < clients.length; j++) {
clients[j] = clients[j-1];
}
}
}
}
}
And here is the Program thread:
package bank.program;
import bank.elements.Account;
import bank.elements.Client;
import bank.elements.Bank;
public class Program {
public static void main(String[] args) {
Bank b = new Bank();
b.addClient();
b.clients[0].setBalance(100);
b.clients[0].addAccount(2);
System.out.println(b.clients[0].getFortune());
}
}
What am I missing?
In your addClient() method :
for (int i = 0; i < clients.length; i++) {
if(clients[i] == null){
clients[i].setId(i);
}
}
So that's totally normal the NPE is thrown because you check if the Client object at the ith position of your array is null and then you're trying to access a method from this object, and hence the NPE.
When you do public Client[] clients = new Client[100];, the 100 slots of the array are initialized to null (default value initialization of an Object in Java).
I would initialize it in your constructor :
public Bank(){
for(int i = 0; i < clients.length; i++){
clients[i] = new Client();
}
}
Change your if in your addClient() method (do if client[i] != null to prevent the NPE), i.e :
for (int i = 0; i < clients.length; i++) {
if (client[i] != null){
clients[i].setId(i);
}
}
The same comment for your Client class with the array of Account.
Also consider to read this : java-What is a Null Pointer Exception?