|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
Homework - Index out of Bounds error
Hey,
I'm doing a program that'll tell me if a given word's a palidrome. Because I'm not too sure where the error is, I'm gonna go against community rules and post the whole code of two programs - one is the method and the other executes the method. Heres the method: Code:
import chn.util.*;
public class PalindromeLab1
{
public String isDouble(String f)
{
int length = f.length();
System.out.println(length);
int c = 0;
for (int i = 0; i <= length; i++)
{
System.out.print(c);
if (f.charAt(i) == f.charAt(length - (i+1)))
{
System.out.print(" ");
c=c+1;
System.out.print(c);
}
else
{
System.out.print(" ");
c=c-1;
System.out.print(c);
}
}
if (c==length)
System.out.println("Yup. It's a palindrome, alright.");
if (c!=length)
System.out.println("No. It's not a palindrome. :( ");
return (" ");
}
}
and here's the code for the executer: Code:
import chn.util.*;
public class PalindromerLabThinger1 {
public static void main(String[]args)
{
ConsoleIO console = new ConsoleIO();
PalindromeLab1 object = new PalindromeLab1();
System.out.print("Enter a palindrome: ");
String palindrome1 = console.readLine();
int length = palindrome1.length();
String thing = object.isDouble(palindrome1);
System.out.print(" " + thing);
}}
It's giving me an index out of bounds for the first one that looks like this (after user input): Enter a palindrome: noon 4 0 11 22 33 44Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4 at java.lang.String.charAt(String.java:558) at PalindromeLab1.isDouble(PalindromeLab1.java:13) at PalindromerLabThinger1.main(PalindromerLabThinger1.java:10) Process completed. Thanks again, dave |
|
#2
|
|||
|
|||
|
I'll give some things to consider...
- the error gives the exact line where the problem is, plus other helpful information - a string of length 4 is indexed 0 to 3 inclusive (i.e. last index is always the length minus 1) - if you're not careful and try to use an index outwith the string's range, you'll get an error - pay attention to the range of values a loop iterates through Hopefully that should help you fix the problem. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Java Help > Homework - Index out of Bounds error |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|