Ok this is a guess a really simple problem which I am having a black out about.... however it is killing my head.
Here is the source:
import java.util.Arrays;
public class InputValues {
public int[] myarrayvar;
public InputValues(int[] myarraypass) {
---- help here
}
public void init() {
---help here
}
public int[] getmyarrayvar() {
return myarrayvar;
}
public void setmyarrayvar(int[] myarraypass) {
this.myarrayvar= mayarraypass;
}
}
I call the this with
InputValues inputValues = new InputValues(myarraypass);
inputValues.init();
myarraypass is of type int[].
Like I said this should be really easy.... but I can't get it to work for some reason....
In case your myarrayvar is public then why would you need a setter and getter. You need them only when your member is inaccessible to the outside world, i.e. it's marked private.
Nest, you can use the following in your constructor for setting the array,
public InputValues(int[] myarraypass) {
this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length );
}
You can try following things:
Change the instance variable access from public to private.
in constructor you can use following line:
this.myarrayvar = myarraypass;
But remember, if myarraypass is modified outside class InputValues, myarrayvar will also be affected.
If you don't want that behavior to occur, you should copy index-by-index.
this.myarrayvar = new int[myarraypass.length];
for(int i=0; i<myarraypass.length;i++)
this.myarrayvar[i] = myarraypass[i];
OR
this.myarrayvar = (int[]) myarraypass.clone();
OR
this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length);
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
Following Question. I have a big amount of ArrayList attributes (basically the same as Kreuzlagerort20kg etc). Instead of initializing them all in the constructor (the part commented out) i'd love to initialize them inside the fillLager() method, making it possible to call the method inside the constructor and have them initialized and filled then. If i do it in the code, i always get a nullpointerexception.
Is it possible and/or sensible to initialize an arraylist inside a method, without getting said nullpointer?
import java.util.ArrayList;
public class Lager {
private ArrayList<Screws> KreuzLagerort20kg,KreuzLagerort50kg;
public Lager(){
//KreuzLagerort20kg = new ArrayList<Screws>();
//KreuzLagerort50kg = new ArrayList<Screws>();
fillLager(1,KreuzLagerort20kg,20);
fillLager(1,KreuzLagerort50kg,50);
}
public void fillLager(int typ,ArrayList<Screws> lager,double lagerGewicht){
lager = new ArrayList<Screws>();
// code that loops through combinations and adds them to the arraylist
}}}}}}
You can't call new on a variable passed into a method and still have the calling method refer to the original variable, as Java passes by reference. When you call new X() then there is a new reference and the method which called your other method will not know the variable is now pointing at another reference...
e.g.
public void methodA() {
String s = new String("AAAAA");
methodB(s);
System.out.println(s);
}
public void methodB(String referredString) {
referredString = new String("BBBBB");
}
calling methodA will print "AAAAA"
You will need to initialise in the constructor, or make the method return the variables you passed in...
public void methodA() {
String s = new String("AAAAA");
s = methodB(s);
System.out.println(s);
}
public String methodB(String referredString) {
referredString = new String("BBBBB");
return referredString ;
}
calling methodA will now print "BBBBB"
Alternatively - make the string declared outside of either method and don't pass it around at all... e.g.
String s = new String("AAAAA");
public void methodA() {
methodB();
System.out.println(s);
}
public void methodB() {
s = new String("BBBBB");
}
will also yield "BBBBB"
You can do it like this:
Instead of normally initializing it (like KreuzLagerort20kg = new ArrayList<Screws>();) in constructor, you do it in fillLager.
import java.util.ArrayList;
public class Lager {
private ArrayList<Screws> KreuzLagerort20kg,KreuzLagerort50kg;
public Lager(){
//KreuzLagerort20kg = new ArrayList<Screws>();
//KreuzLagerort50kg = new ArrayList<Screws>();
fillLager(1, 20);
fillLager(1, 50);
}
public void fillLager(int typ, int code){
if (code==20){
KreuzLagerort20kg = new ArrayList<Screws>();
}
if (code==50){
KreuzLagerort50kg = new ArrayList<Screws>();
}
// code that loops through combinations and adds them to the arraylist
}}}}}}
In a child class GreenSlime Im given a constructor with only three parameters (I cannot add any other instance variables). But the code keeps giving error about this line:super(loc,map,log); which I understand that the constructor should have the same amount of parameters. But my specs say that via the parent constructor, sets all fields. fullcharge must always be 4, and the starting value for charge is 0. I do know that I'm passing only 3 parameters instead of 5, but that's the instructions of my project say so. What am I doing wrong and what's the best approach/solution?
import java.io.PrintStream;
public class GreenSlime extends Threat {
public GreenSlime(Coord loc, Map map, PrintStream log)
{
super(loc,map,log);
super.fullCharge = 4;
super.charge = 0;
}
}
import java.io.PrintStream;
public abstract class Threat extends Thing {
protected int charge;
protected final int fullCharge;
public Threat(Coord c, String repr, int fullCharge, Map map, PrintStream log)
{
super(c,repr,map,log);
this.fullCharge = fullCharge;
charge = 0;
}
public abstract void spawn(Coord c);
#Override
public void doAction()
{
while(charge != fullCharge)
{
System.out.println("\"+repr()"+"#"+"getLoc()\" speading");
if(this.canPassThrough())
{
spawn(getPrevLoc().step(Direction.N));
spawn(getPrevLoc().step(Direction.S));
spawn(getPrevLoc().step(Direction.E));
spawn(getPrevLoc().step(Direction.W));
}
charge++;
}
}
}
public GreenSlime(Coord loc, Map map, PrintStream log)
{
super(loc,"",4,map,log);
}
I've supplied an empty string "" for repr, but you may need null or some other value.
In your code, the Threat constructor has a signature that accepts 5 arguments, but where as you're trying to pass only 3 arguments to it.
For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.
How can I initialize a static, unmodifiable instance of android.util.SparseArray?
Here is a better way using an anonymous class:
static final SparseIntArray myArray = new SparseIntArray() {
{
append(1, 2);
append(10, 20);
}
};
You cannot do what you are attempting to. At least, not how you are attempting to do it. There is no implementation of SparseArray that is unmodifiable.
However, you could create one. Here's how:
Create a class, say CustomSparseArray<E>, and have it extend SparseArray.
Override all methods that change the elements in the array, and replace them with something like this:
#Override
public void append(int key, E value) {
if (mLocked)
return; // Maybe throw an exception
super.append(key, value);
}
Then, add in a member variable to the class, boolean mLocked = false;.
Next, you need a method like the following:
public void lock() { mLocked = true; }
Lastly, implement your static variable using a method similar to in the other post:
public class Test {
private static final CustomSparseArray<Integer> myArray;
static {
myArray = new CustomSparseArray<Integer>();
myArray.append(1, 1);
myArray.append(2, 5);
myArray.lock();
}
}
Then you have an unmodifiable SparseArray in your static variable myArray.
This works for me:
static final SparseIntArray CMyArray = new SparseIntArray();
static {
CMyArray.append(2, 4);
CMyArray.append(8, 3);
CMyArray.append(255, 1);
}
as per: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
I am currently done making a sokoban game with GUI and everything and I am working on optimzation, I would like to keep the objects as sensible as possible and therefore need to be able to call the constructor from a method in the class/object. Suppose:
public class BoardGame() {
public BoardGame)() {
this(1)
}
public BoardGame(int level){
//Do stuff, like calling filelevel-to-board loaderclass
}
How do I create a method that calls the constructor of this object/class in the object/class itself? Eg:
public BoardGame nextLevel() {
return BoardGame(currentLevel+1);
}
The above is apparently undefined!
Such that if I want to use this object in another class I should be able to do:
GameBoard sokoban = new GameBoard(); //lvl1
draw(GameBoard);
draw(GameBoard.nextLevel()); //draws lvl2
You need to use the new keyword to call the constructor.
public BoardGame nextLevel() {
return new BoardGame(currentLevel + 1);
}
Calling the constructor requires the new keyword and always creates a new instance. For instance, in your example code
GameBoard sokoban = new GameBoard(); //lvl1
draw(sokoban );
draw(sokoban.nextLevel()); //draws lvl2
sokoban <-- still level 1
Maybe you want the GameBoard to be mutable:
public class GameBoard {
public GameBoard() {
setLevel(1);
}
private void setLevel(int i) {
currentLevel = i;
....
}
public void nextLevel() {
setLevel(currentLevel+1);
}
}