| |

VerySource

 Forgot password?
 Register
Search
View: 666|Reply: 3

please teach me

[Copy link]

1

Threads

3

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

Post time: 2020-1-21 18:20:01
| Show all posts |Read mode
Below I wrote a small program that displays the first 20 numbers of the Fibonacci series.

It can be displayed at runtime, but it shows an exception in the end. What's the problem? as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20


public class Fibo {
public static void main (String [] args) {
int array [] = new int [20];
array [0] = 1;
array [1] = 1;
System.out.print (array [0] + "");
System.out.print (array [1] + "");
for (int i = 2; i <21; i ++) {
array [i] = array [(i-2)] + array [(i-1)];
System.out.print (array [i] + "");
}
System.out.println ();
}
}
Reply

Use magic Report

0

Threads

12

Posts

7.00

Credits

Newbie

Rank: 1

Credits
7.00

 China

Post time: 2020-1-31 17:45:01
| Show all posts
Array subscript is out of bounds.
int array [] = new int [20]; // This sentence creates an array of 20 ints with subscripts from 0-19;
for (int i = 2; i <21; i ++) {// When the execution reaches i = 20, the conditions are still met, and an exception will be reported when the array [i] is referenced

You can change to int array [] = new int [21];

Or for (int i = 0; i <20; i ++)
Reply

Use magic Report

0

Threads

6

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-2-1 11:27:01
| Show all posts
java.lang.ArrayIndexOutOfBoundsException
Array subscript out of bounds Exception
Learn to look at Exception, it does n’t matter if you do n’t understand, translate it literally, and you can probably guess it
Reply

Use magic Report

1

Threads

3

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

 Author| Post time: 2020-2-1 20:54:01
| Show all posts
ok, got it, thank you
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list