简体   繁体   中英

java String - String index out of range , charAt

I try to make a program which it can find palindromic number (it has to be pruduct of two 3-digits number and I hope that it contain 6 digit but it is not important). Here is my code:

public class palindromicNumber {
    public static void getPalindromicNumber() {
        boolean podminka = false;
        int test;
        String s;
        for (int a = 999; podminka == false && a > 100; a--) {
            for (int b = 999; podminka == false && b > 100; b--) {
                test = a * b;
                s = Integer.toString(test);
                int c = 0;
                int d = s.length();
                while (c != d && podminka == false) {

                    if (s.charAt(c) == s.charAt(d)) { // I think that problem is here but I can't see what
                        System.out.println(s);
                        podminka = true;
                    }
                    c++;
                    d--;
                }
            }
        }
    }
}

and if I want to compile it :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:695)
at faktorizace.palindromicNumber.getPalindromicNumber(palindromicNumber.java:24)
at faktorizace.Faktorizace.main(Faktorizace.java:19)

Java Result: 1

There are two problems here:

  • You're starting off with the wrong upper bound, as other answers have mentioned
  • If c starts off odd and d starts off even, then c will never equal d . You need to use

     while (c < d && !podminka) // Prefer !x to x == false 

Additionally, judicious use of break and return would avoid you having to have podminka at all.

As another aside, you've got a separation of concerns issue. Your method currently does three things:

  • Iterates over numbers in a particular way
  • Checks whether or not they're palandromic
  • Prints the first it finds

You should separate those out. For example:

public void printFirstPalindrome() {
    long palindrome = findFirstPalindrome();
    System.out.println(palindrome);
}

public long findFirstPalindrome() {
    // Looping here, calling isPalindrome
}

public boolean isPalindrome(long value) {
    // Just checking here
}

I suspect findFirstPalindrome would normally take some parameters, too. At this point, you'd have methods which would be somewhat easier to both write and test.

String indices go from [0..length - 1]

Change int d = s.length(); to int d = s.length() - 1;

Update : As a quick aside, you are setting podminka to true when

s.charAt(c) == s.charAt(d)

If s = 100101 for example, you will terminate all of the loops on the first iteration of the while loop because the first and last characters are the same.

int d = s.length();

An array of the strings chars will only go from 0 - length-1.

s.charAt(d) will always be out of bounds on the first iteration.

Take a look on JDK source code:

public char charAt(int index) {
    if ((index < 0) || (index >= count)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index + offset];
}

You can see that this exception is thrown when index is less then zero or exceeds the string length. Now use debugger, debug your code and see why do you pass this wrong parameter value to charAt() .

       public class palindromicNumber {
           public static void getPalindromicNumber(){
              boolean podminka = false;
               int test;
               String s;
            for(int a = 999;podminka == false && a>100; a-- ){
              for(int b = 999;podminka == false && b>100; b-- ){
                test = a*b;
                s = Integer.toString(test); 
                int c = 0;
                int d = s.length();
                while(c!=d && podminka == false){                          

                  if(s.charAt(c)==s.charAt(d - 1)){  
                    System.out.println(s);
                      podminka = true;                                
                }
                      c++;
                       d--;
                 }
                  } 

}

try this! string count starts from 0!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM