Closed Thread Icon

Preserved Topic: Java help Pages that link to <a href="https://ozoneasylum.com/backlink?for=18090" title="Pages that link to Preserved Topic: Java help" rel="nofollow" >Preserved Topic: Java help\

 
Author Thread
butcher
Paranoid (IV) Inmate

From: New Jersey, USA
Insane since: Oct 2000

posted posted 04-26-2001 00:19

I don't know why I'm getting an exception, or what the exception means.
It says StringIndexOutOfBoundsException: String index out of range


Here's the code:

code:
public class OneLine
{
public static void main(String[] args)
{
String sentence;
int sentenceLength;
char punctuation, answer;

do
{
System.out.println("Type in a sentence.");
System.out.println("Make sure to end the sentence ");
System.out.print("with some type of punctuation.");

sentence = SavitchIn.readLine();
sentenceLength = sentence.length();
punctuation = sentence.charAt(sentenceLength);

switch(punctuation)
{
case '!':
System.out.println("Wow");
break;
case '?':
if ((sentenceLength % 2) == 0)
System.out.println("Yes");
else
System.out.println("No");
break;
default:
System.out.println("You always say " + '"' + sentence + '"');
break;
}

System.out.println("Would you like to try again?");
answer = SavitchIn.readLineNonwhiteChar();

}while ((answer == 'y') &#0124; &#0124; (answer == 'Y'));
}
}



Thanks

WarMage
Maniac (V) Mad Scientist

From: Rochester, New York, USA
Insane since: May 2000

posted posted 04-26-2001 03:50

sentenceLength = sentence.length();
punctuation = sentence.charAt(sentenceLength);

The problem is right here.

You have a String "yes" for example.

The length of the string would be reported as 3, yet there is no charAt(3). 'y' is stored at 0, 'e' is stored at 1 and 's' is stored at 2.

So in order for this to work you would need to have,

sentenceLength = sentence.length();
punctuation = sentence.charAt(sentenceLength-1);

I think that this should solve your problem, I have not run the program, or even looked at the program, but off the top of my head this would be what I would see.

-mage-

butcher
Paranoid (IV) Inmate

From: New Jersey, USA
Insane since: Oct 2000

posted posted 04-26-2001 04:03

Thanks Mage

That was it. Don't bother trying to figure why I'm writing the program, it's one of the exercises in the book. I'm back at it finally. Glad to see you with some time to get back around these parts.

[edit]
Oh yea, duh on me for not remembering the 0 index thing.
[/edit]

[This message has been edited by butcher (edited 04-26-2001).]

WarMage
Maniac (V) Mad Scientist

From: Rochester, New York, USA
Insane since: May 2000

posted posted 04-26-2001 07:48

I am always wandering these halls, I just don't poke my info into all of the posts, that is the only way I managed to be here over a year and still have under a thousand posts.

-mage-

« BackwardsOnwards »

Show Forum Drop Down Menu