Returning an array from a Java method - java

I am trying to return two numbers from this method. I thought this was correct. Where am I going wrong?
public int[] getDimension() {
int shapeWidth = 0;
int shapeHeight = 0;
// .....
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
And then at a calling site, is this correct?
public int getWidth() {
return getDimension()[0];
}
I am asking because I believe there's a bug but I don't see it.

That's fine. Short but complete program to demonstrate it working:
public class Test {
public static void main(String args[]) {
int width = getDimension()[0];
System.out.println(width);
}
public static int[] getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
}
You can make the result declaration line slightly simpler, by the way:
int[] result = {shapeWidth, shapeHeight};

Rather than using an array, I would recommend using a class
class Dimensions {
private int width;
private int height;
public Dimensions(int width, int height) {
this.width = width;
this.height = height;
}
// add either setters and getters
// or better yet, functionality methods instead
}
This will give you compile time referential integrity, which is much better than inferring based on "we know index 0 is width and index 1 is height".
If you still want to use an array, Jon's answer is spot on.

Your code looks fine, but try not to use an array if you only need a pair.
Since Java doesn't have tuples/pairs you have to implement them, but it's pretty easy. Refer to this question for a possible implementation.
public class Test {
public static void main(String args[]) {
int width = getDimension().getLeft();
System.out.println(width);
}
public static Pair<Integer, Integer> getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
return new Pair<Integer, Integer>(shapeWidth, shapeHeight);
}
}
This is better than a Dimension class, because you can use it everywhere in your code.

Related

Alternative to pointers in Java

#include<stdio.h>
void decrease(int *i);
int main(){
int i = 10;
decrease(&i);
printf("%d",i);
}
void decrease(int *i){
*i = *i - 1;
}
What would be the Java program for the same?
As you pointed out (no pun intended), Java does not support pointers. So, there is no way to directly manipulate the value of a primitive passed to a method, because only a copy of the primitive would be used in the method. One way to get around this would be to just return the updated value, and then overwrite the integer in the calling scope:
public static int decrease(int i) {
return i - 1;
}
public static void main(String[] args) {
int i = 10;
i = decrease(i);
System.out.println(i); // prints 9
}
You have two options, either (return) the value, and modify it in the main class, or pass an Object, not a primitive.
An object with your values:
public class Holder {
public int x;
}
And a method to modify it
public void modify(Holder h){
h.x = 2;
}
Called like:
Holder h = new Holder();
h.x = 1;
modify(h);
System.out.println(h.x);
Results in:
2

Problems understanding constructors like the one in ArrayList.class

While coding I was trying to declare a class that can create an arraylist of arraylists, but soon enough I found it hard to define a proper constructor for my class. I wanted to define some methods for me to handle the huge outer arraylist(1000*1000), but I might be affected by C and always tried to use something like structdef.
How should I define my class? I guess declaring every lines seperatedly is not a wise choice, and I don't want to use 2D arraylist directly. Besides, how should I define a constructor to get an object that is an 2D arraylist?
//Update here
Below is my code example:
class farbicMap {
//attribute
ArrayList<Integer> farbicUnit = new ArrayList<Integer>();
//constructor
farbicMap () {
for (int i=0;i<1000;++i) {
farbicUnit.add(0);
}//this gives an arraylist with size of 100
//I want to use the above arraylist to construct another list here
}
//method
setUnitValue(int v) {
...
}
}
Seems that I didn't really understand the concept of class... I wanted to use the class to represent a map with some nodes. Now that's much clearer to me.
This is how I understood your consern:
class Test {
public static void main(String[] args) {
Board board = new Board(1000, 1000);
board.put(1, 2, "X");
Object x = board.get(1, 2);
System.out.println("x = " + x);
}
}
class Board {
private final int xSize;
private final int ySize;
private ArrayList<ArrayList<Object>> board = new ArrayList<>();
public Board(int xSize, int ySize) {
this.xSize = xSize;
this.ySize = ySize;
for (int i = 0; i < xSize; i++) {
board.add(getListOfNulls());
}
}
public Object get(int x, int y) {
return board.get(x).get(y);
}
public void put(int x, int y, Object toAdd) {
List<Object> xs = board.get(x);
if (xs == null) {
xs = getListOfNulls();
}
xs.add(y, toAdd);
}
private ArrayList<Object> getListOfNulls() {
ArrayList<Object> ys = new ArrayList<>();
for (int j = 0; j < ySize; j++) {
ys.add(null);
}
return ys;
}
}
You should use Array if size is fixed.

Why am I getting a "; expected" error?

public class homework
{
public static void intPow(int a, int b)
{
Math.pow(a,b);
}
public static void main(String args[])
{
intPow();
}
}
I'm trying to learn how to create a method, but I keep getting 10 ; expected errors. I know this code isn't correct, but I can't seem to find how to create a method correctly. In this case I'm trying to create a method that returns a^b.
You need to pass two int parameters into intPow():
public static void main(String args[])
{
int a = 2;
int b = 5;
intPow(a, b); //32
}
Furthermore, you should probably return an int from intPow() so you can play with it later:
public static int intPow(int a, int b) {
return Math.pow(a, b);
}
Then in main():
public static void main(String args[])
{
int a = 2;
int b = 5;
int power = intPow(a, b); //32
System.out.println(power);
}
pass two int values in intPow();
intPow(5,5);
And anyways the value would not be printed.
You need to use System.out.println() to print it.
Change
intPow();
to
intPow(2,3); // or any number
You declare intPow as a function that takes two parameters. But when you call it from main, you dont pass any. To fix this, change this line in main -
intPow();
to
intPow(1, 2);//or whatever other numbers you want.
public class homework
{
public static int intPow(int a, int b)
{
return Math.pow(a,b);
}
public static void main(String args[])
{
int a = 3;
int b = 4;
int result = intPow(a, b);
System.out.println(result);
}
}
If the goal is to create a method that returns a^b, the method should return a value. You probly need to convert to int though, because Math.pow works with doubles.
public static int intPow(int a, int b) {
return (int) Math.pow(a,b);
}
then call it using two parameters for a and b:
int result = intPow( 2, 3 );

Array of queues not compiling - cannot find symbol error

I'm trying to get a radix sort going with an array of queues to avoid long rambling switch statements but I'm having some trouble getting the array properly initialized. The constructor and an example of an implementation are given below.
I'm just getting a cannot find symbol error when I try to compile though.
public static radixj(){
IntQueue[] buckets = new IntQueue[10];
for (int i = 0; i < 10; i++)
buckets[i] = new IntQueue();
}
public static void place(int temp, int marker)
{
int pos = temp % marker;
buckets[pos].put(temp);
}
I'm pretty sure it is a really simple mistake that I'm making but I can't find it. Any help would be greatly appreciated.
In your code
IntQueue[] buckets = new IntQueue[10];
is a local variable to the function
public static radixj()
which must have a return type
public static void radixj()
So then you can't use it in another function
buckets[pos].put(temp);
You should declare a static class variable
class Foo {
static IntQueue[] buckets = new IntQueue[10];
...
and access it using: Foo.buckets
class Foo {
public static IntQueue[] buckets = new IntQueue[10];
public static void radixj() {
for (int i = 0; i < 10; i++) {
Foo.buckets[i] = new IntQueue();
}
}
public static void place(int temp, int marker) {
int pos = temp % marker;
Foo.buckets[pos].put(temp);
}
}
the return type in radixj() is missing and buckets cannot be resolved to a variable

Calling a method from a class array gives NullPointerException

I've been searching a lot for this problem and I can't find a solution. I'm trying to build a mini-game and I have a method for creating platforms. I have a class with every platform parameters, and I made a class array so i can have multiple platforms at the same time.
Problem: When I try to call the method for constructing the platform by sending the parameters I want, it gives me a NullPointerException. The method was working before, but with everything static and so i couldnt have multiple instances of that class, and now I removed the static fields from the platform class and it gives me the NullPointerException every time I call the method.
I copied the part of the code that gives me the error, the error goes the following way:
public static void main(String[] args) {
Game ex = new Game();
new Thread(ex).start();
}
In Game class:
public Load_Stage load = new Load_Stage();
public Game() {
-other variables initializatin-
Initialize_Items();
load.Stage_1(); // <--- problem this way
In Load_Stage class:
public class Load_Stage {
public Platforms plat = new Platforms();
public void Stage_1(){
Stage_Builder.Build_Platform(200, 500, 300, plat.platform1);
Stage_Builder.Build_Platform(100, 200, 100, plat.platform1);
}
}
And inside the Stage_Builder class:
public class Stage_Builder {
public static final int max_platforms = 10;
public static Platform_1[] p1 = new Platform_1[max_platforms];
public static boolean[] platform_on = new boolean[max_platforms];
public Stage_Builder() {
for (int c = 0; c < platform_on.length; c++) {
platform_on[c] = false;
}
}
public static void Build_Platform(int x, int y, int width, ImageIcon[] type) { // BUILDS A PLATFORM
for (int b = 0; b < max_platforms; b++) {
if (platform_on[b] == false) {
p1[b].Construct(x, y, width, type); // <-- NullPointerException here
platform_on[b] = true;
break;
}
}
}
}
Thanks beforehand.
EDIT: Here's the Platform_1 class (sorry for forgetting about it):
public class Platform_1 {
private int platform_begin_width = 30;
private int platform_middle_width = 20;
public int blocks_number = 0;
public ImageIcon[] platform_floors = new ImageIcon[500];
private int current_width = 0;
public int [] platform_x = new int [500];
public int platform_y = 0;
public int platform_width = 0;
public void Construct(int x, int y, int width, ImageIcon [] type) {
platform_width = width;
platform_y = y;
for (int c = 0; current_width <= platform_width; c++) {
if (c == 0) {
platform_x[c] = x;
platform_floors[c] = type[0];
current_width += platform_begin_width;
} else if ((current_width + platform_middle_width) > platform_width) {
platform_floors[c] = type[2];
blocks_number = c + 1;
platform_x[c] = current_width + x;
current_width += platform_middle_width;
} else {
platform_floors[c] = type[1];
platform_x[c] = current_width + x;
current_width += platform_middle_width;
}
}
}
}
And the Platforms class:
public class Platforms {
public ImageIcon[] platform1 = {new ImageIcon("Resources/Sprites/Stage_Objects/Platform1/begin.png"),
new ImageIcon("Resources/Sprites/Stage_Objects/Platform1/middle.png"),
new ImageIcon("Resources/Sprites/Stage_Objects/Platform1/end.png")};
}
The problem and solution are both obvious.
public static Platform_1[] p1 = new Platform_1[max_platforms];
After this line of code executes, p1 is an array of references of type Platform_1 that are all null.
Executing this line of code tells you so right away:
p1[b].Construct(x, y, width, type); // <-- NullPointerException here
The solution is to intialize the p1 array to point to non-null instances of Platform_1.
Something like this would work:
for (int i = 0; < p1.length; ++i) {
p1[i] = new Platform1();
}
I'm not seeing where you put things in the p1 array in the Stage_Builder class.
Another possibility (unlikely, but possible if you haven't shown everything) is that something in the Platform class, which you didn't show, is not initialized, and is breaking when you call Construct.
Also, the following seems problematic
public static Platform_1[] p1 = new Platform_1[max_platforms];
public static boolean[] platform_on = new boolean[max_platforms];
public Stage_Builder() {
for (int c = 0; c < platform_on.length; c++) {
platform_on[c] = false;
}
}
it appears you declare static variables p1 and platform_on, but you only populate platform_on in a constructor. So the first time you create a Stage_Builder instance, you populate one static array with all false, and don't put anything in the other static array...
Populate those static variables in a static block
// static var declarations
static {
// populate static arrays here.
}
The array you are calling a message on was never filled.
You have
public static Platform_1[] p1 = new Platform_1[max_platforms];
so p1 is
p1[0] = null
p1[1] = null
.
.
.
p1[max_platforms] = null
You try to call
p1[b].Construct(x, y, width, type);
which is
null.Construct(...);
You need to initialize that index on the array first.
p1[b] = new Platform_1();
p1[b].Construct(...);
First of all, your problem is that p1[b] is most likely null, as duffymo pointed out.
Secondly, you are using arrays in a really weird way. What about
a) delete Stage_Builder
b) Instead, have an ArrayList somewhere
c) The equivalent of Build_Platform1() look like this, then:
p1.add(new Platform1(x, y, width, type);
d) no if on[i], no max_platforms, no for loop to add a platform (the latter is a bad performance problem if you actually have a few hundret platforms)

Categories