Reputation: 1
When I try the following code it gives right answer. But when I try to use a.length
it throws ArrayIndexOutOfBoundsException
. How to make my code to use a.length
?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a;
int n = sc.nextInt();
a = new int[n];
for(int i = 0; i <= a.length; i++) {
a[i] = sc.nextInt();
}
for(int i = a.length; i >= 0; i--) {
System.out.println(a[i]);
}
}
Upvotes: 0
Views: 85
Reputation: 35
for(int i=0; i<=a.length; i++) // let say a.length=5;
{ // by default all the element start from
a[i]=sc.nextInt(); //index zero in array 0 1 2 3 4
} //so there is nothing like a[5]
// that's why you are getting arrayOutOfBound
for(int i=a.length; i>=0; i--)
{
System.out.println(a[i]);
}
}
Upvotes: 0
Reputation: 4346
You can make use of String functions in JAVA . The StringBuffer class is like a dynamic string with awesome built in methods .
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String num = String.valueOf(n);
StringBuffer b = new StringBuffer(num);
StringBuffer revNum = b.reverse();
String rev = revNum.toString();
int reversedNumber = Integer.parseInt(rev);
System.out.println(reversedNumber);
}
Upvotes: 0
Reputation: 4418
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int[] a;
int n=sc.nextInt();
a=new int[n];
for(int i=0; i<a.length; i++) // Remove = from for loop
{
a[i]=sc.nextInt();
}
for(int i = a.length - 1; i>0; i--) // Modify here
{
System.out.println(a[i]);
}
}
}
Or for reverse an array you can use directly as below :
Collections.reverse(Arrays.asList(array));
Upvotes: 0
Reputation: 2073
You can only iterate through a.length-1 since the index position start with 0. so in the above case do the below change and it would work as required
for(int i=0; i<a.length; i++)
{
a[i]=sc.nextInt();
}
Upvotes: 0
Reputation: 2013
there is no element in a
at the index a.length
, because index range of a
will be from 0 to (a.length - 1)
. Since there is no index, that will throw the Exception.
Upvotes: 5