Thread: String Problems

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    54
    Rep Power
    1

    String Problems


    Ok, so im working on a mini problem which takes an input and solve it..

    So if the user inputs : 45 + 64. then the code will input an answer.

    However im having trouble with getting the location of the symbol.

    E.G I use substrings to get the values
    Code:
    String X = input.substring(0, SymbolLocation);  
    String Y = input.substring(SymbolLocation + 1, input.length());
    Now the issue is finding the SymbolLocation...

    I used the method "index.of()" but that will only work with ONE symbol. How can i make it find the first instance of any math symbol (+,-,*,/) ?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2010
    Posts
    42
    Rep Power
    4
    You could just do this

    java Code:
    if (input.contains("+"))
            symbol = "+";
    else if (input.contains("-"))
            symbol = "-";
    else if (input.contains("*"))
            symbol = "*";
    else 
            symbol = "/";
     
    int symbolLocation = input.indexOf(symbol);
    String X = input.substring(0, symbolLocation);
    String Y = input.substring(symbolLocation+1);


    Of course that wouldn't work for an input like -10 * 3.
    Last edited by Corpsecreate; May 12th, 2013 at 11:08 PM.
  4. #3
  5. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,020
    Rep Power
    1285
    Have you thought about using a regular expression?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    54
    Rep Power
    1
    I ended up using creating a method, which the parameter is the string input. Then used a for loop to cycle through the string in order to find the instance of a symbol...

    However, i never knew about using regular expressions, so i have to do some research on it.

    But thanks for the help

IMN logo majestic logo threadwatch logo seochat tools logo