Understanding Array code - java

I am learning java, I just want to make sure I am understand this line of code properly. It is as follows:
public class DataStructure {
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
The line I am not sure about is:
arrayOfInts[i] = i;
Is this saying that in the array, index 0 will produce an int value of 0, and index 2 will produce an int value of 2, and so on...?

Just to be clear, because I know this can be confusing, i is an int. By doing:
arrayOfInts[i] = i;
You are finding the i index. Where i is an int. So, if i is 7, it will be the 6th number of the array. Why not the 7th? Because it starts at 0:
(From the java docs)
So, lets say i is 7, right? It will be the 6th number. THAT IS IMPORTANT, and hopefully saves you lots of time with arrays.

Yes, you are correct. arrayOfInts[i] = i; means that at index i of the array arrayOfInts, the value is set to the integer i. So at index 0, it will have a value of 0; index 1 will have a value of 1 and so on. I hope this helps!

Rather than "produing" a value, as you stated, you are assigning a value to that index in the Array. If you were to go through the loop iteratively and wrote down each statement's outcome it would look like this if we use the logical statement arrayOfInts[i] = i
// first iteration
arrayOfInts[0] = 0;
i = i + 1;
// second iteration
arrayOfInts[1] = 1;
i = i + 1;
// third iteration
arrayOfInts[2] = 2;
i = i + 1;
So on and so forth. At the end of the iteration you will have a completely assigned Array that ends in the result
arrayOfInts = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
Also always keep in mind as you learn more programming techniques and languages that in computer science we start counting at 0 instead of 1. It took me quite a while to get that through my head.

Related

Putting an array into a bigger array

I have an array of terms (terms meaning an object with a coefficient and a degree, represented as for example 1.0x^6). The array that I have right now contains 3 terms:
[1.0x^6, 4.0x^5, 10.0x^0].
My goal is to create a bigger array with these terms, but ALSO with terms with a 0 coefficient that are not represented in my array. That probably was not too clear, so here is basically what I want my new array to look like:
[1.0x^6, 4.0x^5, 0.0x^4, 0.0x^3, 0.0x^2, 0.0x^1, 10.0x^0].
Currently, I am iterating through my original array, and if the degree equals the new array.length - 1, I am setting newArray[i] = array[i], if that makes sense. For example, for the first term and i = 0, the degree is 6, and so if 6 = newArray.length - 1 (which is 6), then newArray[i] = array[i].
The problem, however is that array is smaller than newArray, so I am getting an out of bounds error. Any ideas on how to fix this? Sorry for the long post, thanks!
EDIT: Here is my actual code. Sorry if the explanation was unclear.
int max = 0;
Term temp;
for(int i=0; i<array.length; i++) {
max = i;
for(int j=i; j< array.length; j++) {
if(array[j].getDegree() > array[max].getDegree()) {
max = j;
}
}
temp = array[i];
array[i] = array[max];
array[max] = temp;
}
Above, the array is sorted in terms of descending degree. I want to now have the new array contain the old terms, but also 0x^i for all the i that are not used in my set of terms.
Term[] newArray = new Term[this.degree()+1];
for (int c = 0; c < newArray.length; c++) {
if (array[c].getDegree()==newArray.length-1-c) {
newArray[c] = array[c];
}
else {
newArray[c] = new Term(0, newArray.length-1-c);
}
}
There are issues in my code above, and I can see that now because in that for loop, array[c] is not defined for any c > 2. Eclipse is telling my that I have an out of bounds error.
Arrays have a fixed size. If you want to create a bigger array, you need to know the size beforehand and define it accordingly. Also, it seems that you are going through both the arrays using the same iteration variable.
I assume you are doing something like this:
for(i=0;i<newArray.length;i++){
newArray[i] = array[i]; //size of newArray is bigger than array
}
Then you will always get an array index out of bounds exception because "array" is smaller than "newArray" and you go out of bounds when i>=array.length.
You need to fix your code logic.

Prime Numbers Array in Java

I want to return an array that displays all the prime numbers within a certain range from 0 till whatever number I enter.
For the range from 0 to 5 I would like the array returned with [2,3,5]. Within the task I was told by my professor that I should fill the whole array with 0 before replacing those 0 wih prime numbers later.
Currently my code does not return the correct array as I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
My current result array is not [2,3,5] but [5,0,0,0,0].
Any help would be greatly appreciated.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
Arrays.fill(myAry,0);
for(int i=0;i<myAry.length;i++){
for (int nextprime=1; nextprime < bis; nextprime++){
int counter = 0;
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
System.out.print(myAry[i]+" ");
}
return myAry;
}
PS: I have a functioning method (istPrimzahl), which checks if a certain number is a prime number or not.
The problem is that your counter is in the wrong scope.
so instead of incrementing. on every iteration of the first for loop, you declare a new counter. so that it is 0 at the time u assign the prime number to the array.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
// Arrays.fill(myAry,0); // no need, this is already been done at initialization
for(int i=0;i<myAry.length;i++){
int counter = 0;
// adding <= 'nextprime <= bis;' to check also the last number in the range
for (int nextprime=1; nextprime <= bis; nextprime++){
// int counter = 0; wrong scope
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
if(myAry[0] != 0) // to get rid of displaying Zeros
System.out.print(myAry[i]+" ");
}
return myAry;
}
Put below line outside both for loop. That will work.
Reason for issue is - you are resetting the counter while entering the for loop.
int counter = 0;
ArrayList will be a better choice than array. However if using array is another school requirement, then what you have done:
int[] myAry = new int[size];
will already set all elements to zeroes.
There is also no need to use 2 loops for this. Just:
Loop through from 1 to n
if current number is prime, set it to array of current index
idx++
I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
That is because you are setting your counter variable back to zero in every iteration. You should declare it outside your loop.
Example:
int idx = 0; //place this outside the loop
for(int i=1; i<=n; i++)
if(isPrime(i))
myAry[idx++] = i;

Java code 1+ issue

problem with Java code.
import java.util.Random;
public class arrayTable {
public static void main (String[] args) {
System.out.println("Index\t + Value");
int Array[] = new int[10];
Random Object = new Random();
int Values;
// Assigning random values to each element of array
for(int i=0; i<Array.length;i++) {
Values= (1+Object.nextInt(50));
Array[i] = Values;
}
for(int j=0;j<Array.length;j++) {
System.out.println(j + "\t" + Array[j]);
}
}
}
Here with this code i wrote (1+) next to the object so the index should start at 1, however when ever i run the code at always starts at index 0, and it does not matter if i type 2+ or 3+ pr whatever. Could anyone be helpful with pointing out the problem with the code.
thank you in advance.
i wrote (1+) next to the object so the index should start at 1
You wrote 1+ next to the value not the index!
So, what you were doing was:
array[0] = 50 + 1;
Instead of:
array[0 + 1] = 50;
If you wanted to start from index 1 you should write it here:
Array[i + 1] = Values;
However as you're inside a for loop, you could run into an ArrayIndexOutOfBoundsException, so, a better idea would be:
for(int i=1; i<Array.length;i++) { //Look the "i" was initialized with 1 and not with 0.
REMEMBER: ARRAYS START FROM 0 INDEX
If you want to "skip" the first element, then the above modification to for loop should work, but if you want it to run from 1 to 10 then it's a bad idea, because it should be from 0 to 9
You should also be careful to follow the Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently, this will make your code easier to read and understand for you and for us.
Also, try not to name your classes / variables as Java classes names:
Object or Array or List, etc might be wrong choices, also having object lowercase would be a bad idea as it's not descriptive either as suggested by #nicomp on the comments below
but when i type Array [i + 1] it still prints out from index 0, if for example i where to make i dice i would want it to start at index 1, is there no way to do this?
I think you didn't changed the for(int j=0;j<Array.length;j++) { loop, to start from 1
To make a dice I would:
Create the array with 6 slots (starting from 0)
Fill it (1 - 6) like below (inside a for loop):
dice[0] = 1;
dice[1] = 2;
...
dice[5] = 6;
//Example of for loop
for (int i = 0; i < dice.length; i++) {
dice[i] = i + 1;
}
Get a random number (between 0 - 5) called random
Get the value of the array at position random
For example:
random = 3;
//dice[random] = 4;
System.out.println(dice[random]);

How to check index of integer array element in java? [duplicate]

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}
Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.
The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.
For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.
Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}
You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Categories