简体   繁体   中英

Rearranging numbers using variable.charAt(). Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range:

I have looked on other such answers with this error and I can't seem to figure out my code specifically. I am using Java, and I am trying to make a program where I enter a number as an input, and as an output I should get:

example input: 1234
The original number is 1234
The number in reverse is 4 3 2 1

I have this code written:

import java.util.Scanner; //Needed for Scanner class

public class CoeQuiz3
{
  public static void main(String[] args)
  {
    //establish variables
    String ogNumber;
    int ogNumberInt;

    Scanner keyboard = new Scanner(System.in); //establish scanner

    System.out.println("Enter a positive integer greater than 0.");
    ogNumber = keyboard.nextLine();
    ogNumber = checknumber(ogNumber);
    ogNumberInt = Integer.parseInt(ogNumber);

    //print the original number
    System.out.println("The original number is " + ogNumber);

    //print the reverse number
    int ogNumberLength = ogNumber.length();
    int digitposition, ogDigit;
    String reverseStatement = "The number reversed is ";

    for (digitposition = ogNumberLength; digitposition >= 0; 
         digitposition--)
    {
      ogDigit = ogNumber.charAt(digitposition);
      reverseStatement += ogDigit + " ";
    }
    System.out.println(reverseStatement);

it compiles and runs, but every time it gives me the error:

The original number is 1234 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4 at java.lang.String.charAt(String.java:658) at CoeQuiz3.main(CoeQuiz3.java:30)

It should work logically - what is the problem? This problem still occurs if I replace >= with > .

You are trying to access one past the highest available character index in your string. Try this loop instead:

for (int i=ogNumber.length()-1; i >=0; i--) {
    char chr = ogNumber.charAt(i);
    reverseStatement += chr;
}
System.out.println(reverseStatement);

But a nicer way to do this is to use the StringBuffer.reverse() method:

String ogNumberReversed = new StringBuffer(ogNumber).reverse();
for (int i=0; i < ogNumberReversed.length(); ++i) {
    char chr = ogNumberReversed.charAt(i);
    reverseStatement += chr;
}
System.out.println(reverseStatement);

Please change your for-loop as follows:

for (digitposition = ogNumberLength-1; digitposition >= 0; digitposition--){
   ogDigit = Character.getNumericValue(ogNumber.charAt(digitposition));
   reverseStatement += ogDigit + " ";
}

and see the results.

There are two things which have been added:

  1. The for loop counter should start from ogNumberLength-1 not ogNumberLength . This was the reason for java.lang.StringIndexOutOfBoundsException
  2. There is a need to convert the ASCII value of char to number. That is why Character.getNumericValue() has been used.

Hope, it helps!

Alternative solution:

int number = 1234;
String strReversed = new StringBuilder(String.valueOf(number)).reverse().toString().replace("", " ").trim();

System.out.println(strReversed); // 4 3 2 1

Ideone example

See this piece of code

for (digitposition = ogNumberLength; digitposition >= 0; 
     digitposition--)
{
  ogDigit = ogNumber.charAt(digitposition);
  reverseStatement += ogDigit + " ";
}

The first parameter of the loop digitposition = ogNumberLength specifies that the loop should access the char at the position equal to length of the string, and in case of string, the length is equal to the number of characters (for eg length of string "HAPPY" would be 5 not 4). But the index of the last element of the String array is one less than the length of the string (as arrays are zero indexed).

So in practice if you have entered the number "1234":

  • length of string is = 4

  • position of last element array = 3

So your code is trying to access the element number 4 in an array of last index 3, hence the exception.

You should instead write the following (notice the -1 in the 1st parameter)

for (digitposition = ogNumberLength - 1; digitposition >= 0; 
     digitposition--)
{
  ogDigit = ogNumber.charAt(digitposition);
  reverseStatement += ogDigit + " ";
}

This would solve your problem, however if reversing only numbers is your sole objective then I would suggest use the following method as using strings is much more resource intensive

import java.util.Scanner;

class ReverseNumber
{
   public static void main(String args[])
   {
      int n, reverse = 0;

      System.out.println("Enter the number to reverse");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();

      while( n != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + n%10;
          n = n/10;
      }

      System.out.println("Reverse of entered number is "+reverse);
   }
}

Cheers!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:658) Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(String.java:646) using recursion error. Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 Palindrome String Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 Java : Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: How to fix “Exception in thread ”main“ java.lang.StringIndexOutOfBoundsException: String index out of range: 5” problem in Java Error after compiling Java project : Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 0 Why is the program throwing this error??: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 36 Compression class error - Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM