I am new to Java, This may be a silly question but I really need your help.
Code:
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]);
}
Output :
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)
Note: 1st loop works correctly. Then it throws error.
Can someone tell me where my mistake is and why it is not working?