Why is my method populating my array with null? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
I need to create a program to display the content of an array of tables, each table with width and height.
public class Table {
private static int width;
private static int height=20;
private static final Table[] tables = new Table[10];
public Table(int width, int height) {
this.width=width;
this.height=height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public static Table[] getTables() {
return tables;
}
public static int tableWidth(){
int widthMin=50;
int widthMax=200;
width= widthMin+ (int) (Math.random()*(widthMax-widthMin));
return width;
}
public static Table fillArray(){
int i;
for (i=0; i<tables.length-1;i++){
tables[i]=new Table(tableWidth(),height);
}
return tables[i];
}
#Override
public String toString() {
return tables + "";
}
}
public class Main {
public static void main(String[] args) {
for (int i=0;i<Table.getTables().length;i++){
System.out.println(Table.fillArray());
}
}
}
Why isn't the method filling the array, but its presenting null in all positions?

Related

Can interfaces be used as datatypes just like String,int etc [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I was searching the AdapterView.java class. And then I ran into this problem.I have uploaded the java file to the below link
https://www.codepile.net/pile/7J7xq0LY
Here OnItemClickListener is an interface(written on line 278). On line 146 it's given as OnItemClickListener mOnItemClickListener;. How's is that possible .mOnItemClickListener is a member variable. Giving it next to an interface name does'nt make sense for me. When we declare a variable,we first write the variable type followed by the name. But here it doesn't make a logic. Can anyone please explain this to me. I have just learned about interfaces so not much confident with its basics. Thanks in advance
Can interfaces be used as datatypes just like String,int etc.
Yes, an interface is also a type like a class. An interface reference is used in Java to achieve polymorphism.
Check this for more information.
Given below is a sample code to demonstrate this concept:
interface Polygon {
double getArea();
}
class Triangle implements Polygon {
private double base, height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getBase() {
return base;
}
public void setBase(double base) {
this.base = base;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
#Override
public double getArea() {
return 0.5 * base * height;
}
}
class Rectangle implements Polygon {
private double length, breadth;
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getBreadth() {
return breadth;
}
public void setBreadth(double breadth) {
this.breadth = breadth;
}
#Override
public double getArea() {
return length * breadth;
}
}
public class Main {
public static void main(String[] args) {
Polygon shape1 = new Triangle(10, 20);
Polygon shape2 = new Rectangle(10, 20);
System.out.println(shape1.getArea());
System.out.println(shape2.getArea());
}
}
Output:
100.0
200.0
Feel free to comment in case of any doubt/issue.

Basic Java object class returning objects as null? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I just have a basic Class encapulating foods, and when i go to my client class to check the method getName, String and all the other methods, it all returns null. Not sure what is wrong here.
public class Foods {
public String name;
public int calPerServing;
public int servingPerContainer;
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
#Override
public String toString() {
return "Name: " + name + "\nCalories Per Serving: " + calPerServing
+ "\nServings Per Container: " + servingPerContainer;
}
public String getName() {
return name;
}
public int getCalPerServing() {
return calPerServing;
}
public int getServingPerContainer() {
return servingPerContainer;
}
public int getTotalCalories(){
return (calPerServing * servingPerContainer);
}
}
public class Client {
public static void main(String[] args) {
Foods chips = new Foods("chips", 10, 1);
System.out.println(chips.getName());
}
}
This is a typo:
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
Should be:
Foods(String n, int c, int s){
name = n;
calPerServing = c;
servingPerContainer = s;
}

Java performing instance commands before static ones [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I ran into this problem, when an object uses a classes static instance, before it's even created. Example:
class Chair {
public static Chair mychair = new Chair();
public void foo() {}
}
class Table {
public Table() {
Chair.mychair.foo();
}
}
So if I call the mychair.foo() , I get a NullPointerException. I know, not even static things get performed until the class is really needed. But how can I force Java to actually load the class, so it will be created?
Stacktrace of original program:
Exception in thread "main" java.lang.ExceptionInInitializerError
at hu.intelligames.game.level.Level.<init>(Level.java:34)
at hu.intelligames.game.Game.initialize(Game.java:64)
at hu.intelligames.game.Game.<init>(Game.java:43)
at hu.intelligames.game.Game.main(Game.java:80)
Caused by: java.lang.NullPointerException
at hu.intelligames.game.level.tiles.Tile.<clinit>(Tile.java:25)
... 4 more
Constructor of Level class (from line 25):
public Level(int width, int height) {
this.width = width;
this.height = height;
tiles = new Tile[width * height];
for (int i = 0; i < tiles.length; i++) {
if (i % 3 == 0)
tiles[i] = Tile.GRASS;
else if (i % 3 == 1)
tiles[i] = Tile.GRASS;
else
tiles[i] = Tile.STONE;
}
init();
}
Whole code for Tile class:
public class Tile {
public static Spritesheet tileSheet = new Spritesheet("/tiles.png");
public static final Tile VOID = new Tile(0, 0, tileSheet, 0x00000000);
public static final Tile GRASS = new Tile(1, 0, tileSheet, 0xff00ff00);
public static final Tile STONE = new Tile(2, 0, tileSheet, 0xffaaaaaa);
public static final Tile ROAD = new Tile(3, 0, tileSheet, 0xffabcdef);
private Spritesheet sheet;
private int x;
private int y;
private int colorCode;
private static ArrayList<Tile> tileList;
static {
tileList.add(VOID);
tileList.add(GRASS);
tileList.add(STONE);
tileList.add(ROAD);
}
public Tile(int x, int y, Spritesheet sheet, int colorCode) {
this.sheet = sheet;
this.x = x;
this.y = y;
this.colorCode = colorCode;
}
public void render(int xPos, int yPos, int xOff, int yOff, Screen screen) {
screen.render(xPos, yPos, xOff, yOff, x, y, sheet);
}
public int getColorCode() {
return colorCode;
}
public static Tile getTileByColorCode(int code) {
for (Tile t : tileList) {
if (t.getColorCode() == code) return t;
break;
}
return VOID;
}
}
private static ArrayList<Tile> tileList;
Remains null
static {
tileList = new ArrayList<>();
tileList.add(VOID);
tileList.add(GRASS);
tileList.add(STONE);
tileList.add(ROAD);
}
Your field tileList is not initialized, so the static initialization code throws NPE.
This should do the trick:
private static ArrayList<Tile> tileList = new ArrayList<>();

relation between two classes (german code) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I want to make an array with which I can create some instances of the class Schiff (Ship) by using the class Flotte (Armada). Somehow it does not work. Which method is more useful? addShiff or addSchiff2?
public class Schiff
{
private String material;
private int kanonen;
private int ursprungsMäste;
private int mästeStehenNoch;
public Schiff (String material, int kanonen, int mäste)
{
this.material = material;
this.kanonen = kanonen;
ursprungsMäste = mäste;
mästeStehenNoch = mäste;
}
public String gibMaterial()
{
return material;
}
public void mastGetroffen(int wieVieleTreffer)
{
mästeStehenNoch = mästeStehenNoch - wieVieleTreffer;
}
public void wieVieleMäste ()
{
System.out.println("Es stehen noch " + mästeStehenNoch + " Mäste!");
}
}
+++++++
public class Flotte
{
private Schiff [] flottenArray;
public Flotte ()
{
flottenArray = new Schiff [100];
}
public void addSchiff (String material, int kanonen, int ursprungsMäste)
{
for (int zahl = 0; zahl<flottenArray.length; zahl++)
{
if (flottenArray[zahl] == null)
{
flottenArray[zahl] = new Schiff (material, kanonen, ursprungsMäste);
}
}
}
public void addSchiff2 (Schiff neuesSchiff)
{
for (int zahl = 0; zahl<flottenArray.length; zahl++)
{
if (flottenArray[zahl] == null)
{
flottenArray[zahl] = neuesSchiff;
}
}
}
public void gegnerischerFeuerAngriff ()
{
for (Schiff schiff : flotte)
{
if (schiff.gibMaterial().equals("holz"))
{
flottenArray.remove(schiff);
}
}
}
}
What exactly does not work?
Looks good to me.
My feeling is that you can drop the addSchiff (String material, int kanonen, int ursprungsMäste) method because:
One: It is just another way of writing addSchiff2(new Schiff(material, kanonen, ursprungsMäste)) and this is also how it should be coded to avoid repeating yourself:
public void addSchiff (String material, int kanonen, int ursprungsMäste)
{
addSchiff2(new Schiff(material, kanonen, ursprungsMäste))
}
Two: If you later decide to add fields to class Schiff you will have to change the interface of Flotte if you keep the method that constructs a Schiff instance from passed parameters. This is not the case if you just have a method that takes a Schiff instance. So getting rid of addSchiff() decreased inter-class coupling, which is gut.
Klar zur Halse!

Replace conditional with polymorphism, but how to do it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Consider a following piece of code:
class NumberWrapper {
boolean negative;
void setNegativeTrue(boolean isNegative) {
negative = isNegative;
}
void negateNumber(int x) {
if (negative) {
x = x * -1;
} else {
x = Math.abs(x);
}
return x;
}
}
In code like this, how is it possible to use polymorphism ?
You can replace the boolean parameter which results in two different code paths with two different classes, each implementing one path.
abstract class Foo {
abstract void calculate(int x);
}
class NormalFoo extends Foo {
void calculate(int x) {
x = Math.abs(x);
return x;
}
}
class NegativeFoo extends Foo {
void calculate(int x) {
x = x * -1;
return x;
}
}
Instead of setNegativeTrue you create one of those classes and thereby replace the conditional with polymorphism
public enum UnaryOperator {
NEGATE {
#Override
public int apply(int x) {
return -x;
}
},
ABS {
#Override
public int apply(int x) {
return Math.abs(x);
}
}
public abstract int apply(int x);
}
class Foo {
private UnaryOperator operator = UnaryOperator.ABS;
void setUnaryOperator(UnaryOperator operator) {
this.operator = operator;
}
void calculate(int x) {
return operator.apply();
}
}

Categories

Resources