java - How is my String Index Out of Bounds? -


goal: ask user # of points. user input "1 4", 1 x , 4 y. take sub-string 1 , 4 separately make them int can make them point.

i keep getting "java.lang.stringindexoutofboundsexception: string index out of range: -1" this taking place on line 25, not 24. when use 3 instead of length gives me error.

this fragment of code:

public string run() {      string line = "";      string first = "";      string second = "";      int j = 0; int n = 0;     system.out.println("how many inputs want enter?");     scanner sc = new scanner(system.in);      while(j == 0){        if(sc.hasnextint()){         n = sc.nextint();         point[] points = new point[n];         sc.close();         j++;       }         else {         system.out.println("invalid input");       }     }      scanner scan = new scanner(system.in);      for(int = 0; <= n; i++){       system.out.println("enter x , y:");       line = scan.next();       first = line.substring(0,1);       second = line.substring(2,line.length());            }      scan.close();     origin(points);      return "";  } 

see if works you. i'm not sure j variable doing, for-loop points going out of bounds on array, closing system.in between 2 separate scanners, , wrong happening substring logic.

this code fixes problems , runs great me.

public string run() {     scanner sc = new scanner(system.in);      int n = numberprompt("how many inputs want enter?\n", "invalid input");     point[] points = new point[n];      for(int = 0; < n; i++){         system.out.println("enter x , y:");         string line = sc.nextline();         string[] data = line.split("\\s+");         if (data.length >= 2)         {             int x = integer.parseint(data[0]);             int y = integer.parseint(data[1]);             points[i] = new point(x, y);         }     }      system.out.println(arrays.aslist(points));      origin(points);      return ""; }  private int numberprompt(string prompt, string error) {      integer number = null;     boolean isvalid;     string input;     scanner sc = new scanner(system.in);      {         isvalid = true; // reset validity         system.out.print(prompt);         input = sc.nextline();          try {             number = integer.parseint(input);         } catch (numberformatexception e) {             isvalid = false;             if (!(error == null || error.isempty())) {                 system.out.println(error);             }         }     } while (!isvalid);      return number; } 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -