I'm a beginner who is learning on his own.Currently, I am having trouble typing keys in Java.
If you press 1 and press Enter, java.lang.ArrayIndexOutOfBoundsException
appears.
I'm trying to figure out if Enter is causing malfunction, but I still can't think of what to do.I would appreciate it if you could explain the cause and improvement of the malfunction.Also, if there is anything that needs to be improved by looking at the source code, please do not hesitate to write it down.
*The program itself is to display the nth item of the Fibonacci sequence.The work environment is Eclipse.
↓ Source code below
package Fibonacci sequence;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fibonacci {
/*
* I want to show the nth term of the Fibonacci sequence
*/
int fibonacci_number[];
int number;
intn;
// Execute
public static void main(String args[]){
new Fibonacci();
}
public Fibonacci(){
System.out.println("Let me look at the nth term of the Fibonacci sequence.");
System.out.println("You can type as many as you like.");
Scanner scan = new Scanner (System.in); // Key Events
try{
int input = scan.nextInt();
fibonacci_number = new int [ input ]; // array generation
fibonacci_number[0] = 0;
fibonacci_number[1] = 1;
calculation(input);
}catch(InputMismatchExceptione) {// If input is non-numeric
System.out.println("Are you telling me to put in a number?");
return;
}
fibonacci_number = new int [n];
}
public void calculation(intx){
n = x; // Enter characters to n
if(n<3) {// If the input was less than 3
Show if(n==1){//first(0)
printresult(fibonacci_number[0]);
}
else if(n==2){// Display second (1)
printresult(fibonacci_number[1]);
}
} else {// Enter the loop
for(inti=0;i<n-2;i++){
int two_before=i;// 2pcs
int before = i++; // 1 previous
intans=fibonacci_number [two_before]+fibonacci_number [before];
fibonacci_number [i+2] =ans;
}
printresult(fibonacci_number[n]); // Display Calculation Results
}
}
// View Results
public void printresult(ints) {
System.out.println(The number of items in the Fibonacci column is "+s+".");
}
}
Despite generating an array of 1 elements,
fibonacci_number = new int [input]; // Array generation
Accessing the second element,
fibonacci_number[1]=1;
ArrayIndexOutOfBoundsException
is thrown.
Additionally,
int before=i++;
This replaces before with i before +1.
n=x;// Enter the characters to n
You do not need to substitute x
for the variable n
.
new Fibonacci();
There is no need to do new (instance generation).
int number;
The field variable number
is not used, so you should delete it.
fibonacci_number = new int[n];
This line is unnecessary (meaningless).
package Fibonacci sequence;
It is not recommended to use Japanese for package names, etc. (although it is possible).
[Reference]
Use Japanese in Java source code
After about 10 lines of correction, it will work properly.Good luck.
© 2024 OneMinuteCode. All rights reserved.