How to avoid null properties? - java

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?

Related

Swapping between 2 element in ArrayList

I'm new to arrayList and now I am having trouble with the output.
It requires me to take the second char in String Owner compared to other and sort by descending.
I tried by using a variable temp1 to swap 2 of them.
The list before run : (A8,1) (B1,2) (C7,3) (D2,4) (E6,5) (F3,6)
but my output is: (A8,1) (B1,2) (D2,4) (F3,6) (E6,5) (C7,3) (not correct)
#Override
public void f3(List<Cala> list) {
for (int i = 0; i < list.size(); i++) {
char max = list.get(i).getOwner().charAt(1);
for (int j = 1; j < list.size(); j++) {
char temp = list.get(j).getOwner().charAt(1);
if (max < temp) {
Cala temp1 = list.get(i);
list.set(i, list.get(j));
list.set(j, temp1);
}
}
}
}
Please help me what is wrong with this :< Thank you guys
This is my class Cala. I cannot access to Main class because Main's file extension is Main.class
public class Cala {
private String owner;
private int price;
public Cala(){
owner = "";
price = 0;
}
public Cala(String owner, int price) {
this.owner = owner;
this.price = price;
}
public String getOwner() {
return owner;
}
public int getPrice() {
return price;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setPrice(int price) {
this.price = price;
}
#Override
public String toString() {
return "("+ owner + "," + price +")" ;
}
}
I understand that you want to sort the list of Cala objects, by the digit in the owner, using bubble sort algorithm. The following code does that:
import java.util.ArrayList;
import java.util.List;
public class Cala {
private String owner;
private int price;
public Cala() {
this("", 0);
}
public Cala(String owner, int price) {
this.owner = owner;
this.price = price;
}
public String getOwner() {
return owner;
}
public int getPrice() {
return price;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setPrice(int price) {
this.price = price;
}
#Override
public String toString() {
return "(" + owner + "," + price + ")";
}
private static int getDigit(Cala cala) {
if (cala != null) {
String owner = cala.getOwner();
if (owner.length() > 1) {
char digit = owner.charAt(1);
return digit - '0';
}
else {
return 0;
}
}
else {
return 0;
}
}
public static void main(String[] args) {
List<Cala> list = new ArrayList<>();
list.add(new Cala("A8",1));
list.add(new Cala("B1",2));
list.add(new Cala("C7",3));
list.add(new Cala("D2",4));
list.add(new Cala("E6",5));
list.add(new Cala("F3",6));
System.out.println("Before: " + list);
int len = list.size();
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (getDigit(list.get(j + 1)) < getDigit(list.get(j))) {
Cala swap = list.get(j);
list.set(j, list.get(j + 1));
list.set(j+1, swap);
}
}
}
System.out.println(" After: " + list);
}
}
Running the above code produces the following output:
Before: [(A8,1), (B1,2), (C7,3), (D2,4), (E6,5), (F3,6)]
After: [(B1,2), (D2,4), (F3,6), (E6,5), (C7,3), (A8,1)]

how can I remove a room in arraylist Room by name?

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;
}

Calculating discount using multiple methods within the same class

I understand that I do not have anything in my main method yet so nothing will execute, that is the second part to the assignment.
My question is, I'm getting an error in the computeDiscount method where I'm calling the computeNumCases method. The error i'm getting is
variable numCases might not have been initialized
so I need help figuring that error out.
Also, help in the computeCost method would be very helpful as well.
public class Customer {
private String customerLastName;
private String candyType;
private int numCandyBars;
private double costPerBar;
private int NUMBERPERCASE = 12;
public static void main(String[] args) {
}
public Customer() {
}
public Customer(String name, String type, int numCandyBars, double costPerBar) {
//this.name = name;
candyType = type;
this.numCandyBars = numCandyBars;
this.costPerBar = costPerBar;
}
public static double getCostPerBar(double costPerBar) {
return costPerBar;
}
public static int getNumCandyBars(int numCandyBars) {
return numCandyBars;
}
public String getCandyType() {
return candyType;
}
public String GetCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String name) {
this.customerLastName = name;
}
public void setNumCandyBars(int num) {
this.numCandyBars = num;
}
public void setCandyType(String candyType) {
this.candyType = candyType;
}
public void setCostPerBar(double cost) {
costPerBar = cost;
}
public int computeNumCases(int numCases) {
numCases = numCandyBars / NUMBERPERCASE;
return numCases;
}
public int computeNumIndividuals(int numIndividuals) {
numIndividuals = numCandyBars % NUMBERPERCASE;
return numIndividuals;
}
public int computeDiscount(int discount) {
int numCases = computeNumCases(numCases);
if (numCases < 20)
discount = 100;
else if (numCases < 50)
discount = 85;
else
discount = 75;
return discount;
}
public double computeCost(double totalCost) {
return computeNumCases(numCases) * getCostPerBar(costPerBar) * (NUMBERPERCASE * discount / 100.00) + computeNumIndividuals(numIndividuals) * getCostPerBar(costPerBar);
}
}

Add ArrayList into another ArrayList

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);
}
}
}
}
}

Printing an array of objects in Java

I'm making a phone book and filling it with entries. The entries consist of two Strings for surname and initial, and a telephone number. I'm using an array to store the entries. I'm trying to get the array to print out and I've put toString methods in each class. But when I print out i'm still getting "[LEntry;#8dc8569". I'm not sure what I'm doing wrong. Here's the code.
public class Entry {
String surname;
String initial;
int number;
public Entry(String surname, String initial, int number) {
this.surname = surname;
this.initial = initial;
this.number = number;
}
public String getSurname(){
return surname;
}
public String getInitial(){
return initial;
}
public int getNumber() {
return number;
}
void setNumber(int number){
this.number = number;
}
public String toString(){
return surname+ "\t" +initial+ "\t" +number;
}
}
public class ArrayDirectory {
int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
public void addEntry(String surname, String initial, int num) {
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
}
public void deleteEntry(String surname, String initial) {
int i = findEntryIndex(surname, initial);
directory[i] = null;
}
public void deleteEntry(int number) {
int i = findEntryIndex(number);
directory[i] = null;
}
public int findEntry(String surname, String initial) {
int i;
i = findEntryIndex(surname, initial);
return directory[i].getNumber();
}
public void editNum(String surname, String initial, int number) {
int i;
i = findEntryIndex(surname, initial);
directory[i].setNumber(number);
}
public void print() {
// TODO print array
System.out.println(directory);
}
private int findEntryIndex(String surname, String initial) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getSurname().equals(surname) && directory[i].getInitial().equals(initial))
{
break;
}
}
return i;
}
private int findEntryIndex(int number) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getNumber() == number)
{
break;
}
}
return i;
}
private int findFreeLocation() {
int i;
for (i = 0; i < DIRECTORY_SIZE; i++)
{
if(directory[i] == null)
{
break;
}
}
return i;
}
public String toString() {
for(int i = 0 ; i< DIRECTORY_SIZE ; i++){
System.out.println( directory[i] );
}
return null;
}
}
public class Test {
public static void main(String[] args) {
ArrayDirectory phoneBook = new ArrayDirectory();
phoneBook.addEntry("Bigger", "R", 2486);
phoneBook.addEntry("Smaller", "E", 0423);
phoneBook.addEntry("Ringer", "J", 6589);
phoneBook.addEntry("Looper", "T", 6723);
phoneBook.addEntry("Lennon", "B", 4893);
phoneBook.addEntry("Martin", "M", 2121);
phoneBook.print();
}
}
Use Arrays.toString();
Arrays.toString(directory);
when you just print directory, which is an instance of array of type Entry, it doesn't override the toString() method the way you are expecting
Also See
Why isn't there a java.lang.Array class? If a java array is an Object, shouldn't it extend Object?

Categories