public class Maze
{
public static final int ACTIVE = 0;
public static final int EXPLORER_WIN = 1;
public static final int MONSTER_WIN = 2;
private Square[][] maze;
private ArrayList<RandomOccupant> randOccupants;
private Explorer explorer;
private int rows;
private int cols;
public Maze(Square[][] maze, int rows, int cols, int numTreasures, int numMonsters, String name)
{
int i;
this.maze = maze;
this.cols = cols;
this.rows = rows;
randOccupants = new ArrayList<RandomOccupant>();
for (i = 0; i < numTreasures; i++)
{
randOccupants.add(i) = new Treasure(this); //COMPILE ERROR
}...
Why can't I add this to the arraylist? I believe the java docs says that I'm doing this correctly.
You can do either:
randOccupants.add( i, new Treasure(this) );
...or...
randOccupants.add( new Treasure(this) );
Both are equivalent, since you're always appending the new element to the end of the array.
See https://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html.
First, Treasure would need to either inherit from RandomOccupant or implement it (if it is an interface).
Second, if you want to add it at a particular point in the list, the syntax is
randOccupants.add(i,new Treasure(this));
Although it's hard to see why you don't just do
randOccupants.add(new Treasure(this));
since the items will be added in order even if you don't specify a location.
You're trying to add a Treasure to an ArrayList of RandomOccupants, so unless Treasure is a RandomOccupant, that's not going to work. The given code does not make it clear whether Treasure is a subclass of RandomOccupant, so it's not possible from the code here to say whether that's part of the problem.
What you're actually doing is adding an int to the list here, which is definitely not a RandomOccupant.
ArrayList's add() method returns either boolean or void depending on the version that you're using, so you can't assign to it. You're using the method incorrectly.
The two versions of add() are:
boolean add(E e)
void add(int index, E element)
The second version inserts the element at the specified position, and the first one inserts it at the end. Presumably, what you're intending to do is this:
for(i = 0; i < numTreasures; ++i)
randOccupants.add(new Treasure(this));
But of course, that assumes that Treasure is a subclass of RandomOccupant. If it isn't, then you'll need to change the type of the ArrayList for it to hold Treasures.
Because it is not a RandomOccupant.
Because you're using the add method wrong. You would call:
randOccupants.add(new Treasure(this));
Related
I want to add a new element that has several arguments in an array. I know how to add with just one argument, but with more i don't know.
My code is:
private Calculate[] calculation;
public Element(int numElements) {
calculation = new Calculate[numElements];
}
public void addElement(Date elementDate, double price, ElementType type) {
int numElements = elements.length;
int i = 0;
if (i < numElements) {
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
i++;
}
}
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
You shouldn't assign to the same array index 3 times. You're overriding what you've just set.
Try this (Calculate should have a constructor):
Calculate[i] = new Calculate(elementDate, price, type);
You're also maintaining an index i, but you're not looping over anything. i is just incremented from from zero to one and is not really used (apart from an almost useless conditional check).
I suggest you read over a beginners Java tutorial. You seem to be missing a lot of the fundamentals, and Stack Overflow is not a place where we should have to show you how to write a for-loop. It's well-documented and demonstrated in a tonne of tutorials already.
I assume Calculate is a class defined else where with a constructor
There is a couple of issues in this piece of code:
You want to update the array, but specify array. Calculate[] is the array type. The name if the array is calculation. The other thing is that you are trying to access calculation.elementDate etc. but since that is an array, it does not have the field elementDate. I assume your Calculate class has that field. Also, you are not applying a loop. So currently your code will only update the array on index 0.
My code:
public void addElement(Date elementDate, double price, ElementType type) {
for(int i = 0; i < elements.length; i++) { // for loop over all elements in your array
Calculate calculate = new Calculate(elementDate, price, type) // I assume this constructor is available to initialize the Calculate object
calculation[i] = calculate;
}
Hope this helps.
I have two classses and I wonder why I always get an error when I try to create an object of class "Knoten" in a method of class "Graph".
Class Graph
public class Graph
{
static Knoten[] knotenliste;
public void punktHinzufuegen(int x, int y){
for(int i=0;i<Gui.zaehler;i++){
knotenliste[i]=new Knoten(x,y);
}
}
}
Class Knoten:
public class Knoten{
int xPos;
int yPos;
public Knoten(int x,int y){
xPos=x;
yPos=y;
}
}
Every time I call method punktHinzufuegen I get an error. Thanks for helping..
Your problem is a very easy problem to solve, so I'll give a short explanation/solution.
What your current problem is, is that you are not defining your knotenliste.
You should define it as the following field:
private static Knoten[] knotenliste = new Knoten[Gui.zaehler];
I would suggest that you do not use a static value but start working with either a fixed ArrayList (in order to index your graph points) or a Queue. Both of those can be found on the Java documentation if you're intested in reading about them.
What I would have done is the following:
public class Graph {
private final ArrayList<Knoten> knotenliste = new ArrayList<>(Gui.zaehler);
public void punktHinzufuegen(int x, int y) {
for (int i = 0; i < Gui.zaehler; i++) {
// Keep in mind that the List#add(int index, E element) will
// shift all the elements previously in the array to the right.
knotenliste.add(i, new Knoten(x, y));
}
}
}
With this you do not only stop abusing the static keyword, but you also have a more flexible Collection to save your Knoten in.
You haven't initialized your array and I think you are getting NullPointerException while adding elements. You need to initialize it before adding elements to it
static Knoten[] knotenliste = new Knoten[<SOME_INT_VALUE>];
public boolean judge(Parcelle p) {
int xx,yy;
int co;
for(int aa=0;aa<9;aa++) {
for(int bb=0;bb<5;bb++) {
if (p.equals(alist.get(aa).get(bb))) {
xx=aa;
yy=bb;
break;
}
}
}
co=alist.get(xx+1).get(yy).exist+alist.get(xx-1).get(yy-1).exist+alist.get(xx-1).get(yy).exist+alist.get(xx).get(yy-1).exist+alist.get(xx+1).get(yy+1).exist+alist.get(xx).get(yy+1).exist;
return co>=2;
}
Here alist is a 2-dimension arraylist of class Parcelle.
and Parcelle has a public int exist.
I wrote this loop for judge if the sum of the exist of Parcelles around this Parcelle is bigger than 2.
and it alerts that I should initialize the int xx,yy,
but in the loop I've set the value of them.
So I don't know what the problem is!
I don't really get what you're doing here either (no context), but I'd start by setting the variables to zero first:
int xx = 0;
int yy = 0;
int co = 0;
I have a suspicion that is not going to fix everything, but that's where I start when hitting that particular error in java. For some reason, it's really finicky about declaring without setting a value.
I'm trying to make a small game like thing for school. It's designed to help you learn your times tables. What I want is for the multiplier of the table to be random each time (5x8 then 5x3 then 5x9 etc).
I've got the generating of the numbers in control with an array as can be seen below
public static Integer[] generateNumbers()
{
Integer[] arr = new Integer[12];
for(int j = 0; j < arr.length; j++)
{
arr[j] = j+1;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.asList(arr));
return arr;
}
How can I make it so that every time the user clicks a button, the next number in the array is selected, baring in mind that the button is declared in another class, and the ActionListener is also declared elsewhere?
Oh and the array is available class-wide as the function is declared like this:
public static Integer[] arr = generateNumbers();
Thematic answer
public class UnicornFrame extends JFrame {
private Integer[] poneyArr = MyClassThatGeneratesNumbers.generateNumbers();
private int poneyCounter = 0;
private JButton poneyButton;
public void poneyInit() {
System.out.println("Unicorns are poney magical friends!");
poneyButton = new JButton("OMG! Ponies!");
// Java 8 Lambdas! Yey!
poneyButton.addActionListener(e -> {
if (poneyCounter >= poneyArr.length) {
poneyArray = MyClassThatGeneratesNumbers.generateNumbers();
poneyCounter = 0;
}
Integer selected = poneyArr[poneyCounter++];
System.out.println("OMG! I have selected " + selected);
});
// other stuff
add(poneyButton, BorderLayout.CENTER);
}
}
The button int he separate class is not needed, the action listener will communicate with your array whenever its clicked, the easiest way I see is to put a public method int the array's class, that takes an index, which then increments the index, and returns the element stored at it.
Have fun coding, but these assignments are meant for you to scratch your head, try writing some code, and let us know if it breaks, rather than asking for general answers.
I'm new to using OOP, I typically just put all my code in a single class and use methods. But I want to maintain state information and think classes are the best fit but I'm having trouble wrapping my head around it.
Say I have a list of items and I want to stop when the total sum of all previous items in the list equals X(in this case 10 so it takes item 1 + 2, then 2+3.etc..until it hits the threshold 10), I can use a method to calculate it but it involves me doing the entire process all over again when all I really need to do is increment by the last item and then see if my data exceeds the threshold. Here's my code so far but I know its not good because although it works its really just using the class as an independent method and recalculating on every loop. My goal is to,using this structure, reduce loops if not necessary to check thresholds.
Any suggestions?
Code:
public class LearningClassesCounter {
public static void main(String[] args) {
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data(current_location));
for (int i =0; i<100; i++){
if (checker.check_data(current_location) == false) {
break;
}
data_list[current_location] = (list[current_location]+1); //this is just a random function, it could be any math function I just put it in here to show that some work is being done.
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
}
class Counter {
private int[] data_list;
private int total_so_far;
// create a new counter with the given parameters
public Counter(int[] data_list) {
this.data_list = data_list;
this.total_so_far = 0;
}
public boolean check_data(int current_location) {
// TODO Auto-generated method stub
int total_so_far = 0;
//System.out.println(total_so_far);
for (int item : data_list) {
total_so_far = item + total_so_far;
if (total_so_far >= 10) {
break;
}
}
if (total_so_far>=10) {
return false;
} else {
return true;
}
}
}
I don't need anyone to fix my code or anything(I want to do it myself, the code is just to give an idea of what I'm doing). I'm more interested in the flaw in my logic and maybe a way for me to better think about designing classes so I can apply them to my own situations better.
So the solution is that you do not update the data_list directly. Instead have a setter method in the Counter class that takes the index and value to update. It updates the value in the array and also updates a count value.
Something like this:
class Counter{
private final int[] list;
private count = 0;
private final maxCount = 10;
public Counter(int[] list){
this.list = list;
}
public boolean updateValueAndCheckPastMax(int index, int value){
list[index] = value;
count += value;
return count >= maxCount;
}
}
You are way over thinking this, and a counter class is not really necessary in this case.
I'm also interested as to why you'd be doing this line:
data_list[current_location] = (list[current_location]+1);
Do you want your data_list to be the same as list, but each value is incremented by 1?
If you are merely trying to return a sub-array of the values that are < 10, i would suggest just doing this in a for loop, and using an int as a counter.