0
import java.util.*;
class letters
{
    public static void main ()
    {
        char[] ar = new char[10]  ;
        Scanner sc = new Scanner (System.in);
        System.out.println("Enter 10 letters");
        for (int i=0; i<10;i++)
        {
          ar[i] = sc.next().charAt(0);
        }
        for (int i=1; i>=0;i++)
        {
            System.out.println("the letters in reverse are"+ar[i]);
        }
    }
}

So this is my code but when I run it and enter the letters I am getting the following error:

java.lang.ArrayIndexOutOfBoundsException: 10 at letters.main(letters.java:15)
ryanyuyu
  • 5,999
  • 10
  • 46
  • 47

3 Answers3

0

Looking at your code, there are errors in it, I believe what you want to do is to print out the reverse of the input string, which can be achieve with just a single loop like this;

public class HelloWorld
{
   public static void main(String[] args)
   {
     String name = "abcdefghij"; // your input
     for(int i=name.length()-1; i>=0; i--)
     {
       System.out.print(name.charAt(i));
     }
   }
 }
Babajide Apata
  • 527
  • 5
  • 17
  • no i specifically didn't want "abcdefghij" as the input, the input depends on the user so it has to be done in 2 loops only – Mayank Pandey Aug 19 '16 at 14:48
  • Yes, I understand, try to understand the concept of char and string, a string is character array, which I expect you to understand, what you should do is to just substitute your character array in place of variable name in the sample code above. – Babajide Apata Aug 19 '16 at 15:11
  • but then sir what if i am making this program for a friend lets say and he enters some random letters which are not the ones which i had assigned in my program, then there would be an runtime error – Mayank Pandey Aug 19 '16 at 16:58
0

It is showing you error because your have done mistake in second loop where you initialize i with 1 (i = 1) and you run it for infinite loop (i>=0). Thats why it is showing you error Index out of bound. you should start your second loop with i = 9 and run it till (i>=0).

for (int i=9; i>=0;i++)

import java.util.*; class letters { public static void main () { char[] ar = new char[10] ; Scanner sc = new Scanner (System.in); System.out.println("Enter 10 letters"); for (int i=0; i<10;i++) { ar[i] = sc.next().charAt(0); } for (int i=9; i>=0;i++) { System.out.println("the letters in reverse are"+ar[i]); } } }

Kunal Nischal
  • 64
  • 2
  • 6
0

If u want to reverse a String input by the user,then it's better to use StringBuilder class to do so.

This is how to do so.

String str=sc.nextLine();
String rev=new StringBuilder(str).reverse().toString();
asad_hussain
  • 1,684
  • 1
  • 11
  • 24