Topic
IC4NOTICE: developerWorks Community will be offline May 29-30, 2015 while we upgrade to the latest version of IBM Connections. For more information, read our upgrade FAQ.
4 replies Latest Post - ‏2012-06-14T02:02:01Z by callMeBuddy
SystemAdmin
SystemAdmin
210 Posts
ACCEPTED ANSWER

Pinned topic I keep getting the following error and I don't know how to fix it :(

‏2009-10-03T22:23:03Z |
import java.util.Scanner;
public class program3 {

/**
* This program parses and checks simple java declaration statements
* only two types are legal: int and double
*/
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);

String integer = "int";
String Double = "double";
String input;
int loc1, loc2;

System.out.println("Java Declaration Parser");
System.out.println("Enter a Java declaration:");
input = stdIn.nextLine();
String[] in = new String[5];

in = input.split(",");

for(int i=0; i<5; i++){
loc1=in[i].indexOf(' ');
String type = in[i].substring(0, loc1);
if(type.equals("int")|| type.equals("double"))
{
System.out.print("Type: " + type);
}
else
System.out.print("ERROR!" + type + " not found");
}

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at program3.main(program3.java:22)
Updated on 2012-06-14T02:02:01Z at 2012-06-14T02:02:01Z by callMeBuddy
  • Julien Furgerot
    Julien Furgerot
    1 Post
    ACCEPTED ANSWER

    Re: I keep getting the following error and I don't know how to fix it :(

    ‏2009-10-05T09:29:46Z  in response to SystemAdmin
    Hello,

    Take care of what indexOf return.

    > loc1=in[i].indexOf(' ');
    > String type = in[i].substring(0, loc1);

    In your case, it seems there is no space in your input string. So indexOf return -1, and substring(0, -1) send the exception.

    And please, say "hello" and "please" next time :)

    Cordially
    • callMeBuddy
      callMeBuddy
      3 Posts
      ACCEPTED ANSWER

      Re: I keep getting the following error and I don't know how to fix it :(

      ‏2012-06-14T02:02:01Z  in response to Julien Furgerot
      hello !!! please and thanks!!!
  • Sirishap
    Sirishap
    2 Posts
    ACCEPTED ANSWER

    Re: I keep getting the following error and I don't know how to fix it :(

    ‏2011-04-12T10:58:48Z  in response to SystemAdmin
    just checking for my forum...please don't consider this post
  • Sirishap
    Sirishap
    2 Posts
    ACCEPTED ANSWER

    Re: I keep getting the following error and I don't know how to fix it :(

    ‏2011-04-12T11:02:42Z  in response to SystemAdmin
    test::::::::top reply to this thread(kindly don't consider this post)