I have two programs. I create a static array and some methods such as the following:
public Someclass{
static int counter[] = new int[n];
//methods & main
}
the n is defined to be some number, so I know it will have some length. I later fill this array and I test to see that it gets filled correctly, so I know some indexes should have values other than 0. Now when I try to call it in second program, it is though I never filled it because it only gives me 0's.
//second program
public Someclass2{
public static main(String[] args){
String n = "someword"
int[] nums = new int[n.length]
for( int i = 0; i < n.length; i++){
nums[i] = nums[i] + (25 * SomeClass.counter[i]);
}
}
}
For some reason, when I call the array in the second program it returns all zeros and doesnt change the value of nums, even though I know the counter array should have non-zero values. I think it has to do with the fact that I initialize it statically but I filled it in a local method and in the class. So techincally it never gets it's zeroes updated. I am having trouble trying to fix this and if anyone could help I would aprreciate it.
Thank you
My guess: you're filling the array inside of SomeClass, but never call that filling code before using the array in the other class. Solution: be sure to fill it first. For more specific help, show us more details about your code.
Other points -- it is usually best to avoid use of static fields, and instead it is usually better to make the array an instance field. Then you can ascertain its state through its containing class, and also change its state through the containing class with any restrictions that you'd like to put on the ability to change it.
If the second 'program' is really a separate program and not just another class, then it won't work the way you want it to. When the second program calls the static class, it will just create a new array for the second program, while the original array you filled in the first program persists for the first program. Static variables are only accessible to other parts of the same program, not all programs running on the computer.
The problem is here: nums[i] = nums[i] + (25 * SomeClass.counter[i]);
Basically you have created an array and haven't populated it. So if n = 5 then counter == {0,0,0,0,0} . This means that each index gets the default value of 0 so everytime you do this : 25 * SomeClass.counter[i] you multiply with 0 which of course returns 0
There is nothing that happens in Someclass2.main() that would cause the static array in Someclass to be filled. It is all zeroes because that is how the Java spec defines it:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type int, the default value is zero, that is, 0.
The second program never does anything to modify the state of Someclass.counter resulting in getting all zeroes.
Related
I'm not very good at programming but right now, I need to do program a little Java application and I'm running into a weird problem. I've been trying to solve this for hours now.
Here's the problem:
I'm saving a small amount of my screen (20x20) to my program. I do this by looping through every pixel, saving it's RGB into an array via Java.awt.robot. With the following function, the program should save the copied image to 3 arrays (R, G and B) before getting the new area of the screen (I want to compare them later and look for changes). The one damn thing: The old arrays in which I save the data before overwriting the main arrays are always overwriting without me telling them to.
private void fillArrayData(){
oldDataR = dataR; <----- The problem is here. These arrays are now overwritten with the
oldDataG = dataG; <----- current data, just before I write stuff to dataR, G and B.
oldDataB = dataB; <----- As you see, I don't modify oldDataR, G, B later on.
scanArea.x = MouseInfo.getPointerInfo().getLocation().x;
scanArea.y = MouseInfo.getPointerInfo().getLocation().y;
for(int i = 0; i<scanSize; i++){
for(int n = 0; n<scanSize; n++){
dataR[i][n] = (rbt.getPixelColor(scanArea.x+i, scanArea.y+n)).getRed();
dataG[i][n] = (rbt.getPixelColor(scanArea.x+i, scanArea.y+n)).getGreen();
dataB[i][n] = (rbt.getPixelColor(scanArea.x+i, scanArea.y+n)).getBlue();
}
}
}
Even though I never access oldDataR, oldDataG and oldDataB later on, it everytime is equal to the dataR, dataG and dataB after this void finishes. That doesn't make sense as I'm writing new data to the three main arrays (dataR, dataG, dataB) AFTER I saved them to the oldData-Arrays. And yes, I made sure that the data which is received by rbt.getPixelColor is not the same as before.
Please help me, I'm really frustrated by now but need to keep going.
That is happening because oldDataR (and the rest) is just another variable pointing to the same array, if you want to keep the old values in the array separately, and modify the original one, you need to copy it.
This post can be helpful for copying two-dimensional arrays:
copy a 2d array in java
You are passing your arrays as references, so, in the end it is the same array in the pointers of the two variables.
Have you tried array copy?
System.arraycopy()
or
Arrays.copyOf()
Your code would look like:
oldDataR = Arrays.copyOf(dataR);
Edit
I missed the multi dimension of the arrays, just follow #khachik link suggestion so you can handle the two dimensions.
I want to declare integers, while the program is running.
I run the program, and then I give it via System.in.println an integer and repeat this as long as I want.
I want the program to give those integers a name of a certain type for, for example a(i) or a[i], dunno, (it should be handy) and then a(i) represents the the i'th integer I gave the program.
My idea is then that I can use those elements by their name just like, if I had declared them in the first place.
For example add two integers together.
For example I defined a method add+, which waits for 2 integer and then adds them. For example I write:
add
a(2)
a(47)
(then I would get here the result.)
I don't think implementing the add function is difficult. However I don't know, how to let the program count the number of inputs or how to let it declare and use variables.
First: Welcome to programming java; it will be a long road.
Here are some hints:
Use a List<Integer> to hold the sequence of numbers entered by the user.
Actually instanciate a concreate List class, for example LinkedList<Integer>'. If you need to access the elements by index, use anArrayList`.\
Each time the user enters a number, create a new Integer and userList.add(newInteger);
Simple sample
List<Integer> userList = new LinkedList<Integer>();
for (index = 0; index < 9; ++index)
{
Integer newInteger = new Integer(index);
userList.add(newInteger);
}
for (Integer current : userList)
{
System.out.println(current);
}
Yeah, I am following the conversation.
I am just a bit frustrated, because I can't really write any interesting or practical java programs (yet), because my knowledge isn't that big yet.
First I tried to find out, if there was a way to add elements to array, because arrays seemed to me very useful, because each element of an array already has an address. I googled, and it seems that is not possible.
I might be able to use the idea with the list, but it seems to be that the length of the list has to have a limit and actually I wanted to avoid that.
This question already has answers here:
How to test randomness (case in point - Shuffling)
(11 answers)
Closed 8 years ago.
I have written a method to shuffle a String array
So the task is to implement WhiteElephant concept for a given string array of list of names.Should generate assignments to match the original elements.
I have written method to pick a random number and used a map to store the values so that each value will have a different index. But this prints out only 5 values. and i am confused now.
public static String[] generateAssignments(final String[] participants) {
Random r = new Random();
int size = participants.length;
HashMap val = new HashMap();
int change = 0;
String[] assignments = new String[6];
System.out.println("Using arrays");
for(int i=0; i<size;i++){
for(int j =0; j<size; j++){
change = r.nextInt(size);
if(val.containsValue(change) || change==i){
continue;
}
else val.put(i, change);
assignments[i] = participants[change];
System.out.println(assignments[i]);
break;
}
}
return assignments;
}
I appreciate your inputs.
Thanks,
Lucky
If your shuffle method is random (or pseudorandom) it will be near impossible to unit test since the output is non deterministic. If you allow for seeding a random number generator then you could ensure the output is consistent given the same seeds, though this doesn't show randomness.
You could also run the shuffle method a large number of times and check that each card shows up at each index an approixmately equal number of times. Over a large enough number of simulations this should help illustrate randomness.
FYI - There are some logical errors in both your shuffle() code and the test. I won't address those here; hopefully having a good test will allow you to figure out the problems!
Writing tests around Random data is hard.
The best option is to pass in an instance of Random to your shuffle() method or it's containing class. Then in test usages, you can pass in an instance of Random which has been seeded with a known value. Given that the Random code will behave the same every time and you control the input array, your test will be deterministic; you can confidently assert on each object in the sorted collection.
The only downside of this approach is that you won't have a test preventing you from re-writing your shuffle() method to simply re-order the elements every time into this specified order. But that might be over-thinking it; usually we can trust our future selves.
An alternative approach is to assume that in a Random world, given enough time, every data possibility will be realized.
I used this approach when testing a 6-sided die's roll() method. I needed to ensure that getting all values from 1-6 was possible. I didn't want to complicate the method signature or the Die constructor to take in an instance of Random. I also didn't feel confident in a test that used a known seed and simply always asserted 3 (i.e.).
Instead, I made the assumption that given enough rolls, all values from 1-6 would eventually be rolled. I wrote a test that infinitely called roll until all values from 1-6 had been returned. Then I added a timeout to the test so that it would fail after 1 second if the above condition hadn't been met.
#Test(timeout = 1000)
public void roll_shouldEventuallyReturnAllNumbersBetweenOneAndSixInclusively() {
Die die = new Die();
Set<Integer> rolledValues = new HashSet<Integer>();
int totalOfUniqueRolls = 0;
while (rolledValues.size() < Die.NUM_SIDES) {
if (rolledValues.add(die.roll())) {
totalOfUniqueRolls += die.getFaceValue();
}
}
assertEquals(summation(1, Die.NUM_SIDES), totalOfUniqueRolls);
}
Worst case scenario it fails after 1 second (which hasn't happened yet) but it usually passes in about 20 milliseconds.
The test must be reproducible: it is not useful if it depends on something random.
I suggest you to use mocking so the CUT (code under test) don't use the real Random class instantiated in production, but a different class written by you with a predictable behavior, giving you the possibility to make some significant assertions on two or three items.
It appears your shuffle() method will always return the same result. So given a input test array of however many elements in your test, just specify the exact output array you'd expect.
It looks like you are trying to write a very general test. Instead, your tests should be very specific: given a specific input A then you expect a specific output B.
What I'm trying to do is set up 14 arrays that will be of both type string and double to be able to accept input into the first index, and then the next time that the user enters in their information I don't want to add that information into an index that's already been given a value, but I do want to add that new information into the next index of that array. Do I just ++Array[index]? I'm also trying to set up this program to allow the user to be able to access 1 of 3 different IFstatements at a time to input values. If they enter input into an Array in IFstatement1, and then leave IFstatement1, go to IFstatement2 to input something, and then want to come back to IFstatement1 and input data into Arrays there, will the program know to add the newest user inputs into the next index in the array by using the ++Array[index] indicator, or do I have to do something else? How do I accomplish this?
Try looking into the ArrayList object this should work for what you are looking for and it has a nice .add() function to add to the end of the list.
List<String> l1 = new ArrayList<String>();
l1.add("String");
l1.add("Another");
for (String str : l1) {
System.out.println(str);
}
This will add the strings and provide you the iterator.
If you want another with Doubles just change for or you can have one without generics that will just hold objects <> remove them. Then your for loop would traverse the objects instead.
You can't use ++Array[index] to add an element to an array in Java. As in other statically typed languages, array's are given a size when they are created and can't contain more values then their initial size. So for instance int numbers[10]; can hold 10 integer values. If you want to set the values in that array use something like this:
int numbers[10];
for (int i = 0; i < 10; i++) {
numbers[i] = 1 + 1;
}
With regards to the user input you describe, you would need to use some form of looping, maybe a while loop?
I'm a novice programmer. This may be a simple problem but I've never seen this before. First of all, let me clarify that I'm not even trying to manipulate the index. Here's the part of the code that is causing the exception:
int[] bumpercatcher = new int[4];
//time variable that helps control events
int time = 0;
public void setup()
{
bumpercatcher[0]=4;
bumpercatcher[1]=4;
bumpercatcher[2]=4;
bumpercatcher[3]=4;
As you can see I'm trying to set them all equal to 4 at the start of the program. This causes the arrayindexoutofbounds exception. If I set them all equal to 0~3 then there is no problem (until I set them to a value greater than 3 later in the program). I don't understand it.
-it doesn't matter if I set the array size to 10, I still get the same exception
-it doesn't matter if I set only one of the values (i.e. at index 1, which is definitely within bounds of the array). same exception
Is there something I'm doing wrong? Thanks.
well, here' the entire code if you want to take a look(not too long, 1 class, bad programming practies): http://dl.dropbox.com/u/33501308/Pong.java
Here's the html from which you can see the program from (not much to see. it just freezes instantly.): http://dl.dropbox.com/u/33501308/bin.zip
by the way I'm using eclipse.
I don't really know what SSCEE is. sorry
Your posted code file includes loops along the lines of
for(int j: bumpercatcher) {
if(bumpercatcher[j]>5)
...
}
This is an issue. This is a different kind of loop than a traditional for loop. It is an extended or enhanced for, also called a foreach. It reads "for each integer j in array bumpercatcher do x." You are taking your element j (a value) and using it as an index to the array. When your value exceeds the maximum index, you will get an exception.
Write your code with a proper for loop if you want to access by index, or try simply restructuring your logic like
for (int j : bumpercatcher) {
if (j > 5) // j is the value!
...
}
I'm not sure what the problem is, but a far more readable way of doing this would be with a for loop:
for(int i = 0; i < bumpercatcher.length; i++) {
bumpercatcher[i] = 4;
}