I am trying to create a array with Java that can hold as many numbers as the index 'i' is big.
for (int i = 0; i <= 10; i++)
{
int[] zahlenListe = new int[i];
zahlenListe[i] = i + 5;
System.out.println(zahlenListe[i]);
}
but I am always getting the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Start.main(Start.java:27)
Java:27 is this line of code: zahlenListe[i] = i + 5;.
But everything is working fine when I change this line
int[] zahlenListe = new int[i];
to this:
int[] zahlenListe = new int[11];
Anybody cares to explain where the error is?
Array indices are zero based. Hence the maximum index for i sized array is i-1.
An array of length i doesn't have an i'th index. The valid indices go from 0 to i-1.
If you initialize your array with int[] zahlenListe = new int[i+1];, you'll be able to assign a value to zahlenListe[i].
int[] zahlenListe = new int[i];
zahlenListe[i] = i + 5;
Arrays start at index 0.
So index i will never be in an i-dimensional array. It stops at i-1.
For i == 0 the array is empty (no entries at all).
You may want to start your loop at i=1.
From your code it is also not clear why you need an array at all (but you probably have more code in there that you are not showing).
If you creating an array using:
int[] zahlenListe = new int[i];
The last element in array zahlenListe would be zahlenListe[i-1] instead of zahlenListe[i]. In addition, assuming i should start with 1 instead of 0 because an array of length is pointless.
Therefore, use
zahlenListe[i-1] = i + 5;
System.out.println(zahlenListe[i-1]);
You need to start 0 to size-1 in an array as you see;
int[] zahlenListe = new int[i];
Your array size is always i which means you can allowed to access max i-1
Assuming that i always bigger than 0
Basically because in your condition you are telling the computer to go to the 11th element. Think of it this way ...
int i = 0;
First iteration i = 0
if i <= 10; then i = i + 1
Second iteration i = 1
if i <= 10; then i = i + 1
Third iteration i = 2
if i <= 10; then i = i + 1
Fourth iteration i = 3
if i <= 10; then i = i + 1
Fifth iteration i = 4
if i <= 10; then i = i + 1
Sixth iteration i = 5
if i <= 10; then i = i + 1
Seventh iteration i = 6
if i <= 10; then i = i + 1
Eighth iteration i = 7
if i <= 10; then i = i + 1
Ninth iteration i = 8
if i <= 10; then i = i + 1
Tenth iteration i = 9
if i <= 10; then i = i + 1
Eleventh iteration i = 10
if i <= 10; then i = i + 1
Once you get here you are trying to access an element that does not exist. Because your condition says that as long as i is less that or equal that 10, it should repeat the task. If you change <= for < then you stop at the last element available.
Related
Hello guys it might be a dumb question but I am stuck.
I am working on cyclic numbers code. After completing I put all the integers in the array however after that there are some empty cells at the beginning of array that have to be cleaned or put into another array with appropriate amount of elements. So how to get rid of 0 at the beginning.
Here is the code for my cyclic numbers:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int carry = 0;
int[] cyclic = new int[60];
int lastDigit = input.nextInt();
cyclic[cyclic.length - 1] = lastDigit;
for ( int i = cyclic.length - 2; i >= 0; i--) {
cyclic[i] = lastDigit * cyclic[i + 1];
cyclic[i] += carry;
if (cyclic[i] > 9) {
carry = cyclic[i] / 10;
cyclic[i] %= 10;
} else
carry = 0;
if (cyclic[i]==1 & cyclic[i+1]== 0)
break;
}
for (int j = 0; j < cyclic.length; j++)
System.out.print(cyclic[j]);
You are filling the array of 60 elements [0 to 59] in reverse order i.e. from 59 then 58 and then 57 and so on.
While printing you are printing it from indices 0,1,2 and so on.
This is the 1st thing that you should fix fill them from 0,1,2 or print them from 59,58 and so on.
The reason why you are getting 0 is when you say ,
int[] cyclic = new int[60];
cyclic has memory for 60 ints and all the 60 values are now initialized with 0.
Primitive data types are initialized with 0 when you allocate memory to it.
and that's why "the empty cells at the beginning of array" are showing 0 after printing.
I'm trying to increment the following sequence in a for loop (Java):
1, 4, 9, 16, 25 etc the difference increasing by two each time. I tried using 'i+=3 + i' but I know that's wrong since it doesn't take into account that the variable i changes along the sequence.
Any help? Thanks
You could have an increment of i+=k and change k inside the loop in order to change the increment.
int k=1;
for (int i=1;i<1000;i+=k) {
k+=2;
}
If your i is changing, the simple logic is, use another variable that is declared outside the scope of the loop. This will make sure that it is not recreated everytime the loop runs.
int num = 1;
for(int i=1; i<maxValue; num+=2,i+=num){
//Use the value of `i` here, it will be as you wanted.
}
The sequence is to start with j=1 and k=4 and then derive next values of the series n times. The formula as follow:
Initial loop (i=0):
j = 1, k = 4;
Loop (i > 0 less than n):
Repeat below n times:
temp = k;
k = k + (k - j + 2);
j = temp;
print value of j being the series;
I assume that you take n as input from user and then generate the series nth times. Let's look at the following code example
int n = 10;
for(int i = 0, temp = 0, j = 1, k = 4; i < n; i++, temp = k, k += (k-j+2), j = temp) {
System.out.println(j);
}
Assuming that user inputs n = 10, the loop initializes i = 0 and continues until i < n is satisfied. It initializes j = 1 and k = 4 and then execute the body of the loop (printing j) followed by backing up the value of k, calculating new value for k and replacing the old value of j. The output for n = 10 is as follow:
1
4
9
16
25
36
49
64
81
100
Read Series number from the user and generate series based on given number.
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int ans;
for(int i = 1; i <= n; i++){
ans = i * i;
System.out.println(ans);
}
Hello I have searched for a simple way to check ,
if any number of elements up to 6 in the array add up to seven. I have yet to find one my array is this,
private int[] diceRoll = new int[6];
The question is a bit vague, however, here's my attempt at an answer:
If what you're trying to do is take two indices x and y in diceRoll[] and see if they add up to 7, the simplest thing to do is
if(diceRoll[x] + diceRoll[y] ==7){
return true;}
If you're trying to see if ANY item with any other item adds up to 7, use a double for-loop (these are weird, but very helpful)
for(int i = 0; i < diceRoll.length; i++){
for(int j = 0; i < diceRoll.length; i++){
if(diceRoll[i] + diceRoll[j] != 7){
return false;
}
}
}
Hope this helps!
-katie
It sounds like what you need to do is take every subset of the diceRoll array and see which ones add up to 7. This is how it can be done.
Assuming you know that 1 & 1 = 1, and that 1 & 0 = 0, imagine each element of the array having a number in 0 0 0 0 0, if the element is selected, say element 5, the subset representation in binary form would be 0 0 0 0 1. If element 2 and 3 are selected, the subset representation would be 0 0 1 1 0. If you take a binary one, keep track of its index, and move it from right to left in the array computing index&1 each time, you can get which indexes of the array are in the current subset (if the index&1 computation results in a 1 for that index). Translating this to a smaller array called currSubset, you can sum it up and check if it is equal to 7.
The termination of the outer for loop comes from the maximum value of a 5 digit binary number, which is 11111 = 31 = 2^5-1, hence the use of the less than sign.
int sum = 0;
int index = 0;
ArrayList<ArrayList<Integer>> subsetsThatAddTo7 = new ArrayList<ArrayList<Integer>>();
for(int subsetRep = 0b00001; i < Math.pow(2,5); i++){
ArrayList<Integer> currSubset = new ArrayList<Integer>
for(index = 0; index < 5; index++){
if(subsetRep & (1 << index))
currSubset.add(diceRoll[5-index]);
}
int sum = 0;
for(int num : currSubset)
sum += num;
if(sum == 7)
subsetsThatAddTo7.add(currSubset);
}
I'm doing an assignment and something is going wrong but I can't quite figure out what it is. We have to generate a random number between 1 and 25 and add it to an array. When adding the random number to the array, we have to make sure that it isn't already in the array, and if it is we have to generate another random number. Here's my code:
//Variables
Random rnd = new Random();
int rndNum;
int numbers[] = new int[20];
//adds random number to array
for (int index = 0; index < numbers.length; index++)
{
rndNum = rnd.nextInt(25) + 1; //generates random number
boolean same;
if (Arrays.binarySearch(numbers, rndNum) >= 0) //checks for number already in array
same = true;
else
same = false;
//gets another random number if needed
while (same == true)
{
rndNum = rnd.nextInt(25) + 1;
same = Arrays.asList(numbers).contains(rndNum);
}
numbers[index] = rndNum; //adds random number to array
Arrays.sort(numbers); //sorts array for checking purposes
}
//displays array
for (int index = 0; index < numbers.length; index++)
{
//prints numbers in table format
if (index == 4 || index == 9 || index == 14 || index == 19)
System.out.println(numbers[index]);
else
System.out.print(numbers[index] + "\t");
}
This is my output:
0 0 0 0 0
0 0 0 0 0
2 3 4 5 8
12 17 18 19 20
I went through and put break points to see where I was going wrong, but I couldn't see why I was getting a bunch of zeros. What have I done wrong?
The error could be following:
You do:
for (int index = 0; index < numbers.length; index++)
{
// some computation
numbers[index] = rndNum; //adds random number to array
Arrays.sort(numbers); //sorts array for checking purposes
}
You enter the new number and then sort the array. But after sorting, there could be a zero at the entry where you just added a non-zero number (because the array is initialized with zeros).
Try not to sort the array while iterating it.
If you need a set of random values, why wouldn't let a standard set to make all the job?
java.util.Random rnd = new java.util.Random();
java.util.Set<Integer> values = new java.util.LinkedHashSet<>();
while (values.size() < 20) {
values.add(rnd.nextInt(25) + 1);
}
System.out.println(values);
Then copy the set to an array if you prefer.
I need to randomly generate an array with 7 slots in Java. All these slots must have a value of at LEAST 1, but combined, have a total value of another defined number. They also all need to be an int value, no 1.5 or 0.9816465684646 numbers.
Example:
int a=10;
int[] ar = new int[7]
ar[0] = 1
ar[1] = 1
ar[2] = 2
ar[3] = 2
ar[4] = 1
ar[5] = 2
ar[6] = 1
I want it to generate something like that, but if int a=15, all the numbers would total 15 in any order
The standard way to generate N random numbers that add to a given sum is to think of your sum as a number line, generate N-1 random points on the line, sort them, then use the differences between the points as your final values. To get the minimum 1, start by subtracting N from your sum, run the algorithm given, then add 1 back to each segment.
public class Rand {
public static void main(String[] args) {
int count = 8;
int sum = 100;
java.util.Random g = new java.util.Random();
int vals[] = new int[count];
sum -= count;
for (int i = 0; i < count-1; ++i) {
vals[i] = g.nextInt(sum);
}
vals[count-1] = sum;
java.util.Arrays.sort(vals);
for (int i = count-1; i > 0; --i) {
vals[i] -= vals[i-1];
}
for (int i = 0; i < count; ++i) { ++vals[i]; }
for (int i = 0; i < count; ++i) {
System.out.printf("%4d", vals[i]);
}
System.out.printf("\n");
}
}
A good way to achieve uniformity is, for example, to fill up a = 15 units into an 8 element array:
Put 1 in each element in the array as this is your requirement, you have now 7 values left to distribute
Roll a random number between 0 and the max index of the array, and add 1 to that element, and subtract 1 from 7. Do this until 7 goes down to zero.
In this way, you'll meet your minimum conditions by having each element have minimum value 1. Then you distribute the remaining totals in a completely random way.
Adding on to what #Kon said, you could use two random numbers rather than one for more randomness. That is:
Fill every element in the array with the value 1
valuesToDistribute = a - array.length-1
randomIndex = Roll a number between 0 and array.length-1
randomValue = Roll a number between 1 and valuesToDistribute
Add to randomIndex the value randomValue
Subtract randomValue from valuesToDistribute
Repeat until valuesToDistribute = 0
My java is horrible, so I'm not providing the actual code here, as it would probably be wrong. I've done this exact thing in SQL before though, so I know it works...
Let Y be the Total value you want the elements to add up to
Begin a loop with variable Z going from 1 to X where X is the number elements in your array (here called AR)
In the loop, set AR(Z) to a random number between 1 and Y-X+Z
Subtract the new value from Y, so Y = Y - AR(Z)
End loop : back to step 2, advancing Z by 1