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();
}
Related
Cheers, I am pretty new to java and I and I have ran across a problem
I have three classes, all inheriting things between them. Starting I have a class A:
public class A{
private int index;
public A(int index) {
System.out.println("Creating an instance of A");
this.index = index;
}
}
then I have a sublass of A, class M which has a enum inside as:
public class M extends A{
public enum Letter {
A,B,C;
}
private Letter letter;
public M(int index, Letter aLetter) {
super(index);
System.out.println("Creating an instance of M");
this.letter = aLetter;
}
}
and finally a last class P , subclass of M:
public class P extends M {
private T t;
public enum T{
o,
a,
t
}
public P(int index, Letter aLetter, T aT) {
super(index,aLetter);
System.out.println("Creating an instance of P");
this.t = aT;
}
}
What I want to do is create e.g. 3 objects of the class P, and pass on to them RANDOMLY a value of each of these enums. I thought of creating a function in the main class which would be kind of like:
Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
my main looks like this:
int N = 3;
M[] new_m = new M[N]
for(int i = 0; i < N; i++) {
new_m[i] = new P(i, getRandLetter(), getRandT());
}
however I get this error: Cannot make a static reference to the non-static method . What Can I do to achieve what I want?
The error is telling what to do:
Cannot make a static reference to the non-static method
Your main method is static, and the methods called from it should be static as well. So your getRandLetter() and getRandT() methods should be static.
getRandLetter() should look like this:
static Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
And getRandT() should be static as well.
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.
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]);
}
I have some problem with my code.
First of all, here are my codes.
public class Zoo {
public int j=0;
public Animal[] park;
// Exercise 9
public Zoo() {
Animal[] park = new Animal[10];
}
// Exercise 10
public void addAnimal(Animal first) {
for (int i = 0; i < 10; i++) {
if (park[i] != null) {
park[i] = first;
i=j;
i = 10;
} else if (i == 9) {
System.out.println("The zoo is full!");
}
}
}
// Exercise 11
public void feed() {
for (int i = 0; i < 10; i++) {
park[i].mass *= 1.1;
}
}
public String toString() {
String result = "The list:\n";
for (int i = 0; i< 10; i++) {
result = result + "cage " + i + " status:" + park[i] + "\n";
}
return result;
}
public void print() {
System.out.println(park.toString());
}
public int totalLegs() {
int totalLeg = 0;
for (int i = 0; i < 10; i++) {
totalLeg += park[i].legs;
}
return totalLeg;
}
}
ALSO
public class Animal {
float mass;
String name;
int legs;
// Exercise 6-6
public Animal(String randomName) {
name = randomName;
legs = 0;
mass = 0;
}
// Exercise 6-7
public Animal(float one, String two, int three) {
mass = one;
name = two;
legs = three;
}
//Exercise 7
public String toString(){
return "name =" + name + "legs=" + legs + "mass=" + mass;
}
public void massSetter() {
}
public String getName() {
return name;
}
public int getLegs() {
return legs;
}
}
AND
public class TestZoo {
public static void main(String[] args){
Zoo zoo = new Zoo();
Animal elephant = new Animal(300f,"elephant",4);
Animal spider = new Animal(0.5f,"spider",6);
Animal snake = new Animal(10f,"snake",0);
zoo.addAnimal(elephant);
zoo.addAnimal(spider);
zoo.addAnimal(snake);
zoo.print();
System.out.println("Average number of legs is");
}
}
As you probably can tell from the code, I am very new to programming and when I run the last class (TestZoo.java), it gives me the following error.
Exception in thread "main" java.lang.NullPointerException
at Zoo.addAnimal(Zoo.java:13)
at TestZoo.main(TestZoo.java:9)
I did some searching and apparently I get this error when I try to pass a null as if it has something.
I looked at line 13 of the Zoo class and I honesty have no idea how to fix this.
Any help would be greatly appreciated.
Thanks in advance
This is the problem:
public Animal[] park;
public Zoo() {
Animal[] park = new Animal[10];
}
You're declaring an instance variable called park - but then in the constructor, instead of assigning a value to that instance variable, you're creating a local variable called park and assigning a value to that. Change your constructor to:
public Zoo() {
park = new Animal[10];
}
Or you could change the declaration to:
public Animal[] park = new Animal[10];
and remove the explicit constructor declaration entirely.
Either way, the instance variable park will be non-null when you call addAnimal.
Additionally, within addAnimal, there are various issues. For a start, you're continuing to look through park until you find a non-null entry, rather than until you find a null entry... which is the wrong way round.
There are various other things which I'd change about the code (e.g. keep fields private), but hopefully this is enough to get you going.
Within your constructor
public Zoo() {
Animal[] park = new Animal[10];
}
you have shadowed park, as such the instance variable park is never initialised
This means you have created annother variable park that happens to have the same name as the class variable
public class Zoo {
public int j=0;
public Animal[] park; <--This park
public Zoo() {
Animal[] park = new Animal[10]; <--In not the same as this park
}
To correct simply stop creating a new park within your constructor, so
public class Zoo {
public int j=0;
public Animal[] park; <--This park
public Zoo() {
park = new Animal[10]; <--Now is the same as the other park
}
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];