简体   繁体   中英

I keep getting out of bounds error how do i fix this?

Scanner scan = new Scanner(System.in);
System.out.println("Enter a word");
String line = scan.nextLine();
String pig = "";
int a = line.length();

int x = 0;
int y = 0;

while (y < a) {
    int b = line.indexOf(" ");

    if (line.substring(x, x + 1).equals("a") || 
            line.substring(x, x + 1).equals("e") || 
            line.substring(x, x + 1).equals("i") || 
            line.substring(x, x + 1).equals("o") || 
            line.substring(x, x + 1).equals("u"))
    {
        pig = line.substring(x, b - 1);
    }

    else {
        pig = line.substring(b - 1, x + 2) + line.charAt(x);
    }

    line = line.substring(b + 1);
    y++;
}

System.out.println(pig);

I'm suppose to convert the words in any sentence into pig latin if the word starts with a vowel just add way at the end if it starts with a consonant bring the first letter to the back and add way

Stacktrace:

java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at
java.lang.String.substring(Unknown Source) at pig_latin.main(Firstname_Lastname.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:27‌​2

Your method for tracking the words in the line is a problem use String.split(" ") to break the line into a series of words and then your while loop can be

String[] words = line.split(" ");
for(String word:words) {
   // do pig latin on word
}

I suspect it's the substring on line that's failing as you don't terminate correctly when you've processed all words because the variable y is based on characters, where your algorithm is chunking words.

You problem is

int b = line.indexOf(" ");

If you read the java docs . It will return -1 if string is not found. So if b becomes -1 then these lines will be evaluated like:

pig = line.substring(x, -2);

or

pig = line.substring(-2, x + 2) + line.charAt(x);

When you call pig = line.substring(x, b - 1); you are assuming that b is initialized with a positive int, which would only be true if when you evaluate int b = line.indexOf(" "); there actually was a space in the String. If there wasn't, b 's value will be -1, and when you subtract an additional 1 from that, you are attempting to call subString with a value that is out of the String's bounds.

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