java - StringOutofBoundsException -


when put in while loop n, out of bounds exception appears, if take out it's perfect. i'm add data array later on, it's producing error ....

string day = date.substring(0, spacepos);    

the exception follows:

exception in thread "main" java.lang.stringindexoutofboundsexception: string index out of range: -1 @ java.lang.string.substring(unknown source) @ helloworld.main(helloworld.java:21)

scanner userinputscanner = new scanner(system.in);              // i/o stream     string months[] = {"jan","feb","mar","apr","may","jun","jul","aug","sept","oct","nov","dec"};   // months compare     int n = userinputscanner.nextint();      while(n != 0)     {         system.out.print("enter data: ");         string date = userinputscanner.nextline();                  // input , store data         string output;                                              // program output          int spacepos = date.indexof(" ");                           // data before first space         int lastspacepos = date.lastindexof(" ");                   // data after last space          string day = date.substring(0, spacepos);                   // first string         string month = date .substring(spacepos + 1, lastspacepos); // middle string         string year = date.substring(lastspacepos + 1);             // last string          output = year + "-" + month + "-" + day;                    // output new values         system.out.print(output);        } 

could me on error please? if need more data, please ask.

when use int n = userinputscanner.nextint(); leave trailing new-line consumed next nextline() call. empty line , string calls invalid.

int n = userinputscanner.nextint(); while(n != 0) {     system.out.print("enter data: ");     string date = userinputscanner.nextline();     if (date.length() == 0) continue; // <-- retry. 

or, like

int n = userinputscanner.nextint(); userinputscanner.nextline(); // <-- consume trailing newline. while(n != 0) {     system.out.print("enter data: ");     string date = userinputscanner.nextline(); 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -