This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
Here's my code:
int myArray[]={1,2,3,4,5,6,7,8};
for(int counter=myArray.length; counter > 0;counter--){
System.out.println(myArray[counter]);
}
I'd like to print out the array in descending order, instead of ascending order (from the last element of the array to the first) but I just get thrown this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at task1.main(task1.java:14)
Why is this happening? I was hoping that by using myArray.length to set the counter to 8, the code would just print out the 8th element of the array and then keep printing the one before that.
Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
The first index is 0 and the last index is 7 not 8
The size of the array is 8
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
The problem here is this piece of code: myArray.length. In Java, as in most other languages, Data structures are 0 based, so the last element has an index of structure.length - 1 (and the first being 0). So in your case, you should change your loop as follows:
for(int counter=myArray.length - 1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
You're starting at the wrong index. Do it like this:
for(int counter= myArray.length - 1; counter >= 0;counter--) {
The last index of an array is its length minus 1.
the counter is starting at the index of myArray.length which is actually counted from 1 instead of 0..
for(int counter=myArray.length - 1; counter > 0; counter--){
int myArray[]={1,2,3,4,5,6,7,8};
Here, given array length is 8 as the count starts from 1 but coming for the index myArray[0] = 1;
and so on.... here index count starts from 0.
So in your piece of code
for(int counter = myArray.length - 1; counter >= 0; counter--) {
goes out of the array boundary so it shows you ArrayIndexOutOfBoundsException.
Related
This question already has answers here:
Generate random number between two numbers in JavaScript
(32 answers)
Closed 1 year ago.
this code is supposed to display a random character/ letter of a given name in javascript using while loops and if statements . . .
the problem that I faced is that the RandomLetterIndex is between 0 and 5 (<=5) when I want it to be between 0 and 4 (<5)
const MyName = "Ayman";
var RandomLetterIndex = Math.floor(Math.random() * 10);
while (RandomLetterIndex > MyName.length) {
RandomLetterIndex = Math.floor(Math.random() * 10);
if (RandomLetterIndex < MyName.length && RandomLetterIndex !== 5) {
break
}
}
console.log(RandomLetterIndex);
console.log(MyName.charAt(RandomLetterIndex));
If you want the random number to be less than the length of the word, instead of using while loops, you can do this
var RandomLetterIndex = Math.floor(Math.random()*MyName.length);
multiplying by length instead of 10 makes sure that the value always lies in the range [0, length-1] instead of [0, 10-1]
The problem is with the 0 based index and the length property. MyName.length will equate to 5 and thus the while loop will stop and the consoles print out.
while (RandomLetterIndex > MyName.length - 1) {
Try like this with the minus 1.
Your while loop ends when RandomLetterIndex is 5. Thats why you see a five in the console.
Also, you are breaking the loop, and therefore the while check is kind of useless.
Im starting to learn programming, and there is a particular part of the course that is blowing over my head, in the continue section about for loops, im asked to write the output of this code:
var sum=0;
for(i=4; i<8; i++) {
if (i == 6) {
continue;
}
sum += i;
}
document.write(sum);
and for whatever reason, it is supposed to equal 16, i just cant quite picture in my head why, thank you in advance!
Let's follow it through:
sum = 0
At the beginning of the loop, i = 4.
i < 8 is true so the loop continues (yes, this check happens at the very beginning)
Since i == 6 is false, continue doesn't happen
sum += i sets sum to 4
i++ sets i to 5;
i < 8 is true so the loop continues
i == 6 is false so continue doesn't happen
sum += i sets sum to 9
i++ sets i to 6
i < 8 is true so the loop continues
Since i == 6 is true, continue moves on to the next loop iteration, skipping the rest of the loop body
i++ sets i to 7
i == 6 is false so continue doesn't happen
sum += i sets sum to 16
i++ sets i to 8
i < 8 is false so the loop stops
Step #12 is probably the most interesting step: continue skips the rest of the loop body, moving on to the next loop iteration. More about continue on MDN.
Put it another way: The loop sets i to 4, increments i once per loop, and continues while i < 8. That means that within the loop body, i will be 4, then 5, then 6, then 7. In the loop body, sum += i adds i to sum except when i == 6 because continue skips over that part. So sum += i happens for 4, 5, and 7. Since sum starts at 0, it's 0 + 4 + 5 + 7 which is 16.
This is what happens in following loop
initially sum is 0
after first loop i(4) is added to sum
in second loop i(5) is added so sum become 9
in third loop nothing is added to sum because i=6 so continue statement will be executed before adding i to sum
last last loop i(7) is added to sum and result becomes 16.
as condition for loop is i<8 so last value added be 7
I currently have this small script that outputs a value after each iteration of a while loop:
var i = 0;
var number = "";
while (i < 10) {
number += console.log(i);
i++;
}
Which creates this output:
0
1
2
3
4
5
6
7
8
9
However, I am testing some API calls and using the while loop in JavaScript to see if I can send values consistently, so my values are coming from the script below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
i++;
}
I do not need console.log() because I do not need the output in the terminal. My issue is when looking at the output on the receiving end when using the API, it looks something like this:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
The API calls are in the while loop as well, I did not include them because I feel this is a JavaScript syntax related issue. So what will happen is that the while loop begins, number is iterated, that value is sent to a website using an API call, and the the while loop begins again. Something like the code below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
API_Send(number)
i++;
}
What can I do to so that the output of each iteration is its own separate variable similar to the output using console.log(), so first iteration is 0, second iteration is 1, and so on.
I feel this is something that would be necessary when outputting values to be used by a function. So perhaps it is best to create a function that has a while loop outputting integer values?
The problem is that you have declared number as string, don't do that just assign 0 to number variable.
Because of string variable javascript is concatenating the numbers.
Change as following:
var i = 0;
var number = 0;
while (i < 10) {
number += (i);
console.log(number)
i++;
}
This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 7 years ago.
So, in writing a program - in javascript - that sums numbers from 1 to N (number given by user), I have written a working program, but I am still confused as to why one proposed solution that I wrote works, and the other doesn't.
This version works:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = 0;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
This one does not:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = theNum;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
Why doesn't the second one work? If I initially set var onwards as theNum (inputted by a user) and then have the function add onwards to the iterations of 'i' up until the counter reaches theNum, I will see a concatenation between theNum and all the iterations of i next to it, like it is a string. In my mind, setting a variable to the same value and then having that value change to add the counter's iteration should work! Why doesn't it work? Please share.
This is because prompt returns a string, not a number. And when you use "+" operation on a string, you get concatenation, not integer increment. Javascript will not magically convert your string into integer even if it looks like it.
I cam across the following function in javascript:
for (var number = 0; number <= 12; number = number + 2)
show(number);
The Output is the following
0
2
4
6
8
10
12
I expected it to be
2
4
6
8
10
12
14
Why is the "0" shown first and not "2" since the "number = number + 2"comes before the "show(number);"?
This because the order of the loop is like this:
Init number.
Check the condition.
Run the loop.
Increase number by 2.
and then 2-4 again until the condition is false, if so exits the loop.
the for loop translate to something like this:
var number = 0;
while (number <= 12)
{
show(number);
number = number + 2;
}
In general for loop always work like this:
for(Init Variable; Condition ; Changing Variable)
{
//Some Code
}
translates to:
Init Variable
while (Condition )
{
//Some Code
Changing Variable
}
think of it like this :
why did you write the yellow part ?
this is the seed part which you DO WANT TO BE CONSIDERED !
so it will start with its seed value and then - will be incremented ....
0 is the initial value for the number variable in the for loop of the function:
var number = 0;
The for loop is terminated when the number variable reaches 12:
number <= 12;
Here is some more information on for loops: http://www.w3schools.com/js/js_loop_for.asp