Search code examples
javastringtype-conversionrectangles

Java - Converting a string into a rectangle


I am reading a string from a file and I am getting a string variable from it. I would like to convert it into a rectangle variable. I am using the scanner class to read from the file. Here is my code.

    r = new Rectangle[ed];
        for(int i = 0;i < ed; i++){
            String rs = roomInfo.nextLine();
            r[i] = new Rectangle(rs);
    }

In my code I am reading from the file into a string and then you can see how I tried to convert it to a rectangle.


Solution

  • You should in some way parse the String into numbers, then you can create Rectangle objects from it.

    Say, your string looks like this:

    "0, 0, 20, 20"
    

    That's

    "<x>, <y>, <width>, <hight>"
    

    Then here's what you have to do:

    String[] split = str.split("[,]");
    Rectangle rect = new Rectangle(split[0], split[1], split[2], split[3]);
    

    Other string formats require other techniques.