use*_*645 1 java netbeans indexoutofboundsexception
我是Java的新手,这可能是一个愚蠢的问题,但我真的需要你的帮助.
码:
String str[] ={"Enter your name","Enter your age","Enter your salary"};
Scanner sc = new Scanner(System.in);
int[] i = new int[2];
String[] s = new String[2];
int[] y = new int[2];
for(int x = 0 ; x <= 2 ; x++)
{
System.out.println(str[0]);
s[x] = sc.nextLine();
System.out.println(s[x]);
System.out.println(str[1]);
i[x]=sc.nextInt();
System.out.println(i[x]);
System.out.println(str[2]);
y[x]=sc.nextInt();
System.out.println(y[x]);
}
Run Code Online (Sandbox Code Playgroud)
输出:
run:
Enter your name
Sathish
Sathish
Enter your age
26
26
Enter your salary
25000
25000
Enter your name
Enter your age
23
23
Enter your salary
456
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at javaapplication1.JavaApplication1.main(JavaApplication1.java:121)
456
Enter your name
Java Result: 1
BUILD SUCCESSFUL (total time: 34 seconds)
Run Code Online (Sandbox Code Playgroud)
注意:第一个循环正常工作.然后它抛出错误.
有人能告诉我我的错误在哪里以及为什么它不起作用?
这条线会造成错误
for(int x = 0 ; x <= 2 ; x++)
Run Code Online (Sandbox Code Playgroud)
改成
for(int x = 0 ; x < 2 ; x++)
Run Code Online (Sandbox Code Playgroud)
完整的代码
public static void main(String[] args) {
String str[] = {"Enter your name", "Enter your age", "Enter your salary"};
Scanner sc = new Scanner(System.in);
int[] i = new int[2];
String[] s = new String[2];
int[] y = new int[2];
for (int x = 0; x < 2; x++) {
System.out.println(str[0]);
s[x] = sc.nextLine();
System.out.println(s[x]);
System.out.println(str[1]);
i[x] = sc.nextInt();
System.out.println(i[x]);
System.out.println(str[2]);
y[x] = sc.nextInt();
System.out.println(y[x]);
sc.nextLine();// add this line to skip "\n" Enter key
}
}
Run Code Online (Sandbox Code Playgroud)
........................说明......................... .........
错误在这里
for (int x = 0; x =< 2; x++) {
s[x] = sc.nextLine();// when x=2 error occurs
Run Code Online (Sandbox Code Playgroud)
因为s数组的长度为2,只有2个元素,但数组索引是零基础,你不能得到s[2].
第二个问题是" But 1st loop works correctly. when loop 2 starts its not allowing me to type Name .its directly goes to age .Do you know why ?"
好..
input.nextInt()只读取int值.当你继续阅读时,input.nextLine()你会收到"\n"回车键.所以要跳过这个你必须添加input.nextLine()
要获得有关此第二个问题的更多解释,您必须阅读此问题使用nextInt()后跳过nextLine()
| 归档时间: |
|
| 查看次数: |
264 次 |
| 最近记录: |