0
Wanna print index I.where is problem?
public class Main { public static void main(String[] args) { int[] a = { 4, 8, 2 }; for (int i = 0; i <= 3; i++) { System.out.println(a[i]); } } }
11 Respostas
+ 5
Somvardhan Shiva
Try this
public class Main
{
public static void main(String[] args)
{
int[] a = { 4, 8, 2 };
for (int i = 0; i < 3; i++)
{
System.out.print("Index : " + i);
System.out.println(" Value : " + a[i]);
}
}
}
+ 4
Abhay
Java don't give garbage value. It will throw an exception ArrayIndexOutOfBoundsException.
+ 2
Somvardhan Shiva
print i then not a[i] if you want to print index.
There is one more problem array contains 3 elements but you have used array index from 0 to <=3 which is wrong which may give you Exception.
There should be
for (int i = 0; i < 3; i++)
+ 1
Abhay please write code in details. Didn't get.
+ 1
🅰🅹 🅐🅝🅐🅝🅣 it's not working. I tried.
+ 1
🅰🅹 🅐🅝🅐🅝🅣 sorry but i was just talking about it in general but thks for correcting me here . And also i assumed that there is some language that might throw some garbage value.
+ 1
🅰🅹 🅐🅝🅐🅝🅣 thanks it worked.
+ 1
Abhay
Yes in C language we get.
0
indexing in array starts from zero .At index 0=>4, 1=>8, 2=>2 .
But your for loop will try to get the value at index 3 for which there exists no value and hence the error
0
Your array only has 3 values , while you are getting the values at index a[0], a[1], a[2], a[3] , how do you expect the computer to return a value at a[3] ? It will either throw a error or return some garbage value.
0
Should be only i<3 in the for loop