简体   繁体   中英

Why do I get a out of bounds message when I try to run this code?

I am trying to match a pattern. Everything works except when I try to add a string like "1??2" with 2 "?" instead of 3 "?" I get the following error:"String index out of range: 4". Please see my code below:

import java.util.Scanner;
import java.util.regex.*;
public class pattern {

   public static void main(String[] args) {
       // TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String str, result="";
int  myArray = 0;
System.out.println("Enter a string: ");
str =in.next();

String REGEX = "[0-9]\\?{3}[0-9]";

Pattern pattern =Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(str);
boolean matches =matcher.matches();
if (matches = true) {
    result=str;
   } else {
   System.out.print("False");
}

int resultLen= result.length();
int sum=0;
for (int i=0; i <resultLen-1; i++) {
   char newChar=result.charAt(i);
   int first= result.charAt(0)-'0';
   int last=result.charAt(4)-'0';
   sum=first+last;
}
System.out.print(sum==10? "True": "False");



   }

}

Corrected code based on the comments by Elliot Frisch:

public static void main( String... args ) 
{
  System.out.println( "Enter a string: " );
  final var in = new Scanner( System.in );
  final var str = in.next();

  final var regex = "[0-9]\\?{3}[0-9]";
  final var pattern = Pattern.compile( regex );
  final var matcher = pattern.matcher( str );

  if( matcher.matches() ) 
  {
    final var first = Character.getNumericValue( str.charAt( 0 ) );
    final var last = Character.getNumericValue( str.charAt( 4 ) );
    final var sum = first + last;
    
    System.out.print( sum == 10 ? "True" : "False" );
  } 
  else 
  {
    System.out.print("False");
  }
}

In the original code there was an assignment instead of a comparison:

…
boolean matches = matcher.matches();
if( matches = true ) // WRONG!
{
  …

instead of

…
boolean matches = matcher.matches();
if( matches == true )
{
  …

or

…
boolean matches = matcher.matches();
if( matches )
{
  …

Next, the original program proceeded even the given input string did not match the regular expression, with the result that an exception could be thrown in such case.

Finally, the loop did not have any impact on the final value of sum , and was therefor superfluous.

Also several local variables were obsolete; they did not even support readability.

And that hack with substracting '0' to get the numeric value works, but is not intuitive; it also works only for digits in the ASCII realm.

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