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]); } } }

8th Jun 2021, 8:52 AM
Somvardhan Shiva
Somvardhan Shiva - avatar
11 ответов
+ 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]); } } }
8th Jun 2021, 9:22 AM
A͢J
A͢J - avatar
+ 4
Abhay Java don't give garbage value. It will throw an exception ArrayIndexOutOfBoundsException.
8th Jun 2021, 9:24 AM
A͢J
A͢J - avatar
+ 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++)
8th Jun 2021, 9:03 AM
A͢J
A͢J - avatar
+ 1
Abhay please write code in details. Didn't get.
8th Jun 2021, 9:15 AM
Somvardhan Shiva
Somvardhan Shiva - avatar
+ 1
🅰🅹 🅐🅝🅐🅝🅣 it's not working. I tried.
8th Jun 2021, 9:17 AM
Somvardhan Shiva
Somvardhan Shiva - avatar
+ 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.
8th Jun 2021, 9:34 AM
Abhay
Abhay - avatar
+ 1
8th Jun 2021, 10:05 AM
Somvardhan Shiva
Somvardhan Shiva - avatar
+ 1
Abhay Yes in C language we get.
8th Jun 2021, 3:25 PM
A͢J
A͢J - avatar
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
8th Jun 2021, 9:01 AM
Abhay
Abhay - avatar
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.
8th Jun 2021, 9:21 AM
Abhay
Abhay - avatar
0
Should be only i<3 in the for loop
9th Jun 2021, 6:13 PM
Raveen Panditha
Raveen Panditha - avatar