Java ArrayPointStoreException and NullPointerException - java

This is my code. A simple demonstration of method overriding.
public class Bond {
void display() {
System.out.println("Bond");
}
}
public class ConvertibleBond extends Bond {
void display() {
System.out.println("ConvertibleBond");
}
}
public class Pg177E2 {
public static void main(String[]args) {
int random = (int)(10*Math.random());
Bond bond[] = new ConvertibleBond[6];
for(int i = 0; i < 6 ;i++) {
if(random < 5) {
bond[i] = new Bond(); // the problem occurs here
} else if(random > 5) {
bond[i] = new ConvertibleBond();
}
}
for(int i = 0; i < 6; i++) {
bond[i].display();
}
}
}
This would be simple enough and it should work; however, it is coming up as an ArrayPointStoreException and NullPointerException. Can anyone please help me out? I have no idea what I did wrong. Everything looks placed in order. The classes are all in the same package.

Bond bond[] = new ConvertibleBond[6];
bond[i] = new Bond();
You have an array of ConvertibleBond. It can only take instances of that, not any old Bond.
You probably wanted
Bond bond[] = new Bond[6];

Related

Non-deterministic behavior with Java Multithreading

I wrote a simple program that I am using to practice multithreading in Java. The goal is to test whether or not a Sudoku solution is valid: No repeating numbers in rows, columns, or sub-grids. At this point I don't care that the entries must be from 1-9. The program works fine when the Sudoku solution is invalid. When the Sudoku solution is valid (on the same input), the program works only sometimes. Specifically, "win" may or may not be printed.
My program works by creating RowThread, ColumnThread, and GridThread. Each are of them check whether the solution has valid rows, columns and grids, respectively. When a thread is finished checking, it calls the appropriate setter method in SudokuTest, which will call the end method in Main if the solution is invalid. If the thread does not determine that the solution is invalid, the setter method will record that the row, column, or grid has been checked, and then call the allChecked method. allChecked checks if row, column, and grid have been checked. If so, then the solution is valid, so it calls Main.success(), which should print "win." Here is my Main class:
public class Main{
public static void end(){//called by SudokuTest when the solution is invalid
System.out.println("fail");
System.exit(0);
}
public static void success() {//called by SudokuTest when the solution is valid
System.out.println("win");/*this line will not always print,
but it is reached in the debugger when I set a breakpoint.*/
System.exit(0);
}
public static void main(String[] args) {
int[][] sudokuSolution = new int[9][9];
int k = 0;
for (int i = 0; i < 9; i++) { //loop fills up a 2d array with the numbers 0-80, a valid solution
for (int j = 0; j < 9; j++) {
sudokuSolution[i][j] = k;
k++;
}
}
//sudokuSolution[1][1] = 0;//Testing an invalid solution
SudokuTest t = new SudokuTest();//
Runnable r = new RowThread(sudokuSolution, t);
Runnable c = new ColumnThread(sudokuSolution, t);
Runnable g = new GridThread(sudokuSolution, t);
new Thread(r).start();
new Thread(c).start();
new Thread(g).start();
}
}
My RowThread class:
public class RowThread implements Runnable {
int[][] _sudoku;
SudokuTest _t;
public RowThread(int[][] sudoku, SudokuTest t) {
_sudoku = sudoku;
_t = t;
}
private void isFail() { //issue: how to get this info back to my Main function?
for(int i = 0; i < _sudoku.length; i++) {
for(int j = 0; j< _sudoku.length; j++) {
for (int k = j+1; k< _sudoku.length; k++) {
if (_sudoku[i][j] == _sudoku[i][k]) {
_t.setRow(true);
return;
}
}
}
}
_t.setRow(false);
}
#Override
public void run() {
isFail();
}
}
My ColumnThread and GridThread classes are the same as RowThread, except for the logic in the isFail() method.
My SudokuTest class:
public class SudokuTest {
public boolean _rowBad;
public boolean _colBad;
public boolean _gridBad;
public boolean _rowChecked;
public boolean _colChecked;
public boolean _gridChecked;
public SudokuTest(){
}
public void setRow(boolean b) {
_rowBad = b;
_rowChecked = true;
if (b) {
Main.end();
}
}
public void setCol(boolean b) {
_colBad = b;
_colChecked = true;
if (b) {
Main.end();
}
}
public void setGrid(boolean b) {
_gridBad = b;
_gridChecked = true;
if (b) {
Main.end();
}
allChecked();
}
public void allChecked() {
if (_gridChecked && _colChecked && _rowChecked) {
Main.success();
}
}
}
Answer: as Maarten Bodewes pointed out, my mistake was to not call allChecked in setCol and setRow.

I am getting the reference as output. What should i include in my program to get the output

package basicprograms;
public class Progrm {
public long[] ph;
public Progrm(long[] ph){
this.ph=ph;
}
}
The main method:
package basicprograms;
import java.util.ArrayList;
public class UseProgrm {
public static void main(String[] args) {
ArrayList<Progrm> ar = new ArrayList<>();
Progrm p1 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
Progrm p2 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
Progrm p3 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
ar.add(p1);
ar.add(p2);
ar.add(p3);
for (int i = 0; i < ar.size(); i++) {
System.out.println(ar.get(i));
}
}
}
By default, all classes in Java inherit from the Object class. In this case what you are actually printing is Progrm::toString method that is inherited for the Object class and by default is returning the hash. If you would like to print the content of the array(public member ph of the Progrm class) then you should override the toString of Progrm as follows:
public class Progrm {
public long[] ph;
public Progrm(long[] ph) {
this.ph=ph;
}
#Override
public String toString() {
return "Progrm{" +
"ph=" + Arrays.toString(ph) +
'}';
}
}
and the output will be:
Progrm{ph=[942758427, 4298578432, 3425962]}
Progrm{ph=[942758427, 4298578432, 3425962]}
Progrm{ph=[942758427, 4298578432, 3425962]}
For more info on Object::toString, you can refer to :
Why does the default Object.toString() include the hashcode?
You have to override the toString() method in your Program class
now, the System.out.println statements are calling the default implementation of the Object class.
Add this to your Program class:
public String toString() {
StringBuilder b = new StringBuilder("");
for ( long p : ph) {
b.append("Value: " + p + ", ");
}
return b.toString();
}
Afterwards, you can modify it to fit your needs.
Try this:
for (int i = 0; i < ar.size(); i++) {
for(int j = 0; j < ar.get(i).ph.length; j++)
System.out.println(ar.get(i).ph[j]);
}

How to add multiple instances of class in an array loop?

Main class is Zoo, Animal class performs Polymorphism by calling the pinStick method from each different Animal (other classes)
In the zoo array loop, int r's value is decided by Math.random which is 1 or 0 each time, resulting in a squeak, or a roar, depending which animal class is called.
My question is, how can I include an instance of the class Monkey to be printed every time the Mouse or Lion is called (in the if statement)
The aim is add a new instance of the monkey class so that in the result printout you have “OoOoAhAh” together with “Squeak” and “Roar”
public class Zoo {
private Animal[] animals;
public Zoo() {
animals = new Animal[10];
}
public void talkAnimals() {
int r;
for (int i = 0; i < 10; i++) {
r = (int) Math.round(Math.random());
if (r == 0) {
animals[i] = new Mouse();
} else{
animals[i] = new Lion();
}
}
for (int i = 0; i < 10; i++) {
animals[i].pinStick();
}
}
public static void main(String[] args) {
// TODO code application logic here
new Zoo().talkAnimals();
}
}
public class Animal {
protected String name;
public Animal(){
}
public void pinStick(){
}
}
public class Mouse extends Animal {
public void pinStick(){
System.out.print("Squeak!");
}
}
public class Monkey extends Animal {
public void pinStick(){
System.out.print("OoOoOoAhAhAh!");
}
}
public class Lion extends Animal {
public void pinStick(){
System.out.print("Roar!");
}
}
The aim is add a new instance of the monkey class so that in the result printout you have “OoOoAhAh” together with “Squeak” and “Roar”
You can just declare another array for Monkey
private Animal[] monkeys;
constructor
monkeys = new Monkey[10];
and pushes new Monkey object in for loop
for (int i = 0; i < 10; i++) {
r = (int) Math.round(Math.random());
if (r == 0) {
animals[i] = new Mouse();
} else{
animals[i] = new Lion();
}
monkeys[i] = new Monkey();
}
then later on in the for loop just do the printing job
for (int i = 0; i < 10; i++) {
animals[i].pinStick();
monkeys[i].pinStick();
}

How can I add info to a object class?

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();
}
Now I want to add a client to cashier[0] i do this:
cashier[0].cashierclients.addLast(l.get(0));
everything works fine but when I want to print the size of cashier[1] it returns 1 but it should return 0 because I did not add any person to cashier[1]. Any ideas as to what is wrong?
// the error happens here
cashier[1].cashierclients.size();
the program is working now and it shows the error in cashier[1] size that should return 0 instead of 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());
}
}
The following code
for(int i=0; i<10; i++){
cashier[i].cashierclients=empty;
}
makes cashier[i].cashierclients point to the same object
so you can find
System.out.println(cashier[0].cashierclients == cashier[1].cashierclients);
equals to true
i think you shall change empty to new LinkedList()
that will fix the probelm

JUnit - Test Max Number of Objects Created

I have a very small class, BuildThreeObjects, which creates a maximum of 3 Objects using a private int variable, numObjects, to store the count. If the count is < 3, a new Object is returned else null is returned.
Could anyone guide me on how to test if a maximum of 3 Objects are created using JUnit. Looking at the API didn't help much. I assumed assertNotNull or assertNull would be used but I can't think how to.
// Code for BuildThreeObjects class
public class BuildThreeObjects {
private int numObjects = 0;
public Object buildObject() {
if (numObjects<3) {
numObjects++;
return new Object();
}
else return null;
}
}
// Code within the JUnit class; all unnecessary code omitted
private BuildThreeObjects bto;
#Before
public void setUp() throws Exception {
bto = new BuildThreeObjects();
}
#Test
public void testBuild() {
assertNotNull(bto.buildObject());
}
// assertNotNull passes and assertNull fails as it only checks the first object creation
You mean something like this?
class BuildThreeObjects{
int count = 0;
public Object buildObject(){
if(count >= 3){
return null;
} else {
count++;
return new Object();
}
}
}
private BuildThreeObjects bto;
#Before
public void setUp() throws Exception {
bto = new BuildThreeObjects();
}
#Test
public void testBuild() {
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNull(bto.buildObject());
System.out.println(bto.count);
}
// with for loop
for(int i=0; i < 100; i++){
if(i < 3){
assertNotNull(bto.buildObject());
System.out.println(bto.count);
} else {
assertNull(bto.buildObject());
System.out.println(bto.count);
}
}
Just literally do it:
assertNotNull(createObject());
assertNotNull(createObject());
assertNotNull(createObject());
assertNull(createObject());
you could use for-loop also if it could be more expressive.

Categories

Resources