Read last char of a String

I have the following code that functions like a basic RPN calculator:
public class Main {
     * @param args the command line arguments
     static public ArrayList<Double> stack = new ArrayList<Double>();
     static double numberInput;
     static double answer;
     static String operation;
//Prints Welcome screen, initialized checkforInput
     public static void main(String[] args) {
         System.out.println();
         System.out.println("Welcome to RPNCalc by theCoffeeShop()");
         checkForInput();
//Checks for input, redirects to appropriate method
     public static void checkForInput() {
         Scanner reader = new Scanner(System.in);
      String input = reader.nextLine();
         if(isDouble(input) == true) {
            double number = Double.parseDouble( input );
            stack.add(0, number);
            repeat();
         } else {
            operation = input;
            operation();
//Processes numeric operations
     public static void operation () {
         if(operation.equals("+")) {
             answer = stack.get(1)+stack.get(0);
             stack.add(0, answer);
             System.out.println(answer);
             repeat();
         } else if (operation.equals("-")) {
             answer = stack.get(1)-stack.get(0);
             stack.add(0, answer);
             System.out.println(answer);
             repeat();
         } else if (operation.equals("*")) {
             answer = stack.get(1)*stack.get(0);
             stack.add(0, answer);
             System.out.println(answer);
             repeat();
         } else if (operation.equals("/")) {
             answer = stack.get(1)/stack.get(0);
             stack.add(0, answer);
             System.out.println(answer);
             repeat();
         } else {
             System.out.println("Incompatible operation");
             repeat();
//Called when ready to recheck for input
     public static void repeat() {
         checkForInput();
//Checks if string is double
     public static boolean isDouble( String input )
        try
            Double.parseDouble( input );
            return true;
        catch(Exception e)
           return false;
}To perform a basic operation (5+2), you would do the following
5
enter
2
enter
(plus)
enter
Computer prints 7.
I would like it to function like this:
5
enter
2(plus)
enter
Computer prints 7.
To do this, I have to be a be to split a string into 2 parts, the operation and the number. I think I could do this with a StringBuffer, but How to read the LAST char of a StringBuffer, instead of just a specific char? If there is a way to do it w/out a StringBuffer, I'm open to suggestions.

Hint:
The last character of a String (or StringBuilder or StringBuffer, etc.) is at the index (length_of_string - 1).
Are you sure you're supposed to solve the problem this way? Usually homework assignments of this sort involve writing a whole parser.

Similar Messages

  • How to delete the last char in a String?

    i want to delete the last char in a String, but i don't want to convert the String to a StringBuffer or an array, who knows how to do?

    Try it in this way
    String MyString = "ABCDEF";
    MyString = MyString.substring(0,MyString.length()-1);

  • How to remove last char in a string by space

    I have to implement backspace application(remove a last char in a string , when we pressed a button).
    for ex: I enter the no
    1234
    instead of 1236
    So when i press a button on the JWindow... it should display
    123
    so that i can enter 6 now.
    I tried to display the string "123 " instead over "1234" but it is not working when the no background is specified. but works fine when a background color is specified.
    The string is displayed as
    Graphics2D g = (Graphics2D)window.getGraphics();
    AttributedString as = new AttributedString(string, map);
    g.drawString(as.getIterator(),x,y);
    In the map, the background is set to NO_BACKGROUND.
    Thanks and regards

    Deja vu. I saw this kind of post before, and I'm sure
    it was today.http://forum.java.sun.com/thread.jspa?threadID=588110&tstart=0
    Here it is.

  • Deleting last char in a string...

    I have a string that is created as follows: strBuffer += k.getKeyChar();(k is KeyPressed ...KeyEvent) How can I delete the last Char in the string strBuffer?

    Hi
    // simply substring
    if (strBuffer.length() > 1)
        strBuffer = strBuffer.substring(0, strBuffer.length()-1);
    // you may also use
    if (strBuffer.length() > 1)
        StringBuffer buffer = new StringBuffer(strBuffer).
                                   deleteCharAt(strBuffer.length()-1);
        strBuffer = buffer.toString();
    }I've not tested the above code myself & I've written the above code on the go after reading your query. The above code definitely work & help you.
    Regards,
    JPassion

  • Deleting the last char of a string

    How can I Delete the last char of a string???
    example:
    asd@fdg@vvdfgfd@gdgdfgfd@gdfgdf@
    I want delete the last @!
    Tks in advance!

    hi,
    try this:
    lv_count = strlen(string).
    lv_count_last = lv-count - 1.
    replace string+lv_count_last(lv_count) in string by ' '.
    This should work.
    thnx,
    ags.
    Edited by: Agasti Kale on Jun 4, 2008 9:03 PM

  • Finding last char in the string

    Hi
    i need to find out whether the last char of a string is '/' (forward slash). please let me know if there's a FM to do that. Other post me the logic for this ASAP.
    thanks

    len = strlen(char).
    len = len - 1.
    if char+len(1) = '/'.
      *write ur code
    endif.
    chk this code
    REPORT ychatest.
    DATA : str(5) VALUE '123/',
           len TYPE i.
    len = STRLEN( str ).
    len = len - 1.
    IF str+len(1) = '/'.
      WRITE : '/ found'.
    ENDIF.
    <b>Reward points if helpful and close thrad if solved</b>
    Message was edited by: Chandrasekhar Jagarlamudi

  • Remove last char of string

    Hi Guys
    How can I remove the last char of a String ?

    With [the substring method|http://java.sun.com/javase/6/docs/api/java/lang/String.html#substring(int,%20int)] .

  • The last character of a string

    How to judge the last char of a string is " ?
    if (s.endsWith("""))or
    if (s.endsWith("/""))

    bet
    you just copied and pasted what the OP had written
    and quickly put that
    backslash in, hit post without previewing first just
    to make me look like
    a slow old sod! It's not fair ;-)
    kind regards,
    JosNope, I used the Alt-[numeric code] combinations to manually type each character. Cut-n-paste is for wimps, and actually typing single-stroke keys is for milquetoasts.
    Alt-[numeric code] is for real men ;-)

  • Remove last char

    Ok i am trying to make just a simple calculator program for a class. I am trying to get the backspace button to work. How would i delete the last char in the string.

    use a substring, the last char. will be:
    myString.length
    that will give you the length and from that you know what the last char. is

  • How to take last 5 char from a string

    Hi All
    I have a requirement,
    base on some comp i have to populate another field.
    in this case i have compare last 3 char of a string 
    example if total string say asasdffrx i have to take last three char here it is frx.
    always i have to last 3 char.
    i can use +6(3) but it wont work every time because string lenght is not fix for all vaue.
    thanks

    Hi,
    A.H.P sample is ok but insert additional check for strigs shorter than 3 (to avoid negative offset):
    data : n TYPE I.
    n = STRLEN( zfield ) - 3.
    if n >= 0.
    result = zfield+n(3).
    else.
    result = zfield.
    endif.
    Krzys

  • Compare the last Char to the First Char in a Sting

    Hello, this should be easy but I'm having problems so here goes.
    I get the user to input a Stirng and I want it to compare the last Char to the first Char. I have writen this but StartWith can take a Char?
    public static void main(String[] args) {
            // TODO code application logic here
            String strA = new String();
            int length = 0;
            char lastLetter;
            System.out.println("Please input your first String: ");
                   strA = EasyIn.getString();
                 length = strA.length()-1;
                   lastLetter = strA.charAt(length);
           if( strA.endsWith(lastLetter))
                System.out.println("The first letter matches the last");
           else
                       System.out.println("They Don't match");
    }I have tried lastLetter.endsWith(strA) but that dosn't work some thing to do with it not taking Char
    From reading you can go strA.startWith("R") and that would look for R but you can't put a char in that would be a single letter.
    I also tried to lastletter to a string but then charAt wouldn't work.

    fixed it I used substring as its a string object any one recomend a better way let me know
    public static void main(String[] args) {
            // TODO code application logic here
            String strA = new String();
            int length = 0;
            String lastLetter;
            System.out.println("Please input your first String: ");
                   strA = EasyIn.getString();
                 length = strA.length()-1;
                   lastLetter = strA.substring(length);
           if( strA.startsWith(lastLetter))
                System.out.println("The first letter matches the last");
           else
                       System.out.println("They Don't match");
    }

  • Verify special char is in String before append into StringBuffer

    I have following code to verify A special char "X" is in the String before continue adding it to a StringBuffer:
    private boolean veriChar(String poem){
    if(peom.indexOf("X")==-1) return false;// make sure X is in the String
    return true
    However, if I only want a single X in String to return true, any method to use? for example: poem=" EXTRA TEXT" (2 Xes here) needs to be rejected to be false.

    take this code compile it and see for yourself.
    public class Test{
      public static void main(String args[]){
        Test t = new Test();
        System.out.println(""+t.veriChar("MATT"));
        System.out.println(""+t.veriChar("MAX"));
        System.out.println(""+t.veriChar("MAXX"));
      private boolean veriChar(String toCheck){
        return!((toCheck.indexOf("X")<0)||(toCheck.indexOf("X")!=toCheck.lastIndexOf("X")));
    } you will see that the first and third ones return false and the second returns true which is as you want.
    now an explanation of what is happening.
    the method looks like this
    private boolean veriChar(String toCheck){
        return!((toCheck.indexOf("X")<0)||(toCheck.indexOf("X")!=toCheck.lastIndexOf("X")));
      }first we check if the special X or whatever exists in the string at all
    toCheck.indexOf("X")<0;this returns true for the first test of MATT
    now we check if the last occurance in our string of the special X is the same position as the first occurance. if it is then we have only one special X. if not then we have more than one special X.
    toCheck.indexOf("X")!=toCheck.lastIndexOf("X")note that we check for not equals so that for MAX it returns false and for MAXX it returns true
    so now we have our answers but they are inverted from what we want so we put the ! which gives the boolean opposite. so that the MAX returns true and the other two return false.

  • Cutting last char in the XI

    hello experts
    I have a scenario RFC2WS and sending
      <?xml version="1.0" encoding="UTF-8" ?>
    - <rfc:ZRFC_POLICY_OR_INSURANCE xmlns:rfc="urn:sap-com:document:sap:rfc:functions">
      <PASSWORD>kf001</PASSWORD>
      <USERNAME>kfirg001</USERNAME>
      </rfc:ZRFC_POLICY_OR_INSURANCE>
    but in the XI I am recieving
      <?xml version="1.0" encoding="UTF-8" ?>
    - <rfc:ZRFC_POLICY_OR_INSURANCE xmlns:rfc="urn:sap-com:document:sap:rfc:functions">
      <PASSWORD>kf00</PASSWORD>
      <USERNAME>kfirg00</USERNAME>
      </rfc:ZRFC_POLICY_OR_INSURANCE>
    it is always cutting the last char in the username\password. in the RFC it is defined as a String.
    I couldnt find out why it is cutting the last char and help would be great.
    Thanks
    Kfir

    Hi,
    Is it possible for you to send it with Filed type as CHAR instead of String..
    In RFC source code you could handle this kind of conversion.
    Try with CHAR...instead of string.
    Thanks
    Swarup

  • Truncating last character in a string

    I am making a dialpad. It is just for display so I am using a
    string for the numbers selected. I am trying to make a back button
    that would clear the last number added. I tried mystring.length-1
    but that doesn't seem to be doing the trick. Is there a simple way
    to truncate the last character in a string, of variable
    length??

    Here's an example
    var someStr="asdfasdf saf asdf sadfas dfs fsa asf";
    while (someStr.length) {
    someStr = someStr.substring(0,someStr.length-1)
    trace(someStr);
    }

  • How to remove only the last element of spreadsheet string

    I use path to string option to store image path into database and while retrieving the string is again converted into path but it gives out an error as the output of array to spreadsheet string gives out a tab at the end which is unable for the IMAQ read file to recognise.but when i use the path of the image directly into IMAQ readfile the image is opened . so how to remove the tab only at the end of output of the spreadsheet string(whose length can vary)? I have also attached my program with this.
    Attachments:
    retrieve_images_from_DB.vi ‏65 KB
    file_path_to_db_(images).vi ‏40 KB
    create_table_for_images.vi ‏45 KB

    indhu wrote:
    > Thanks for your reply!
    > But my problem is to remove only the last element(which is a tab or an
    > alphabet) from a spreadsheet string of any length.
    If you just want to remove the last character of a string just use the
    String Size function reduce the result by one and wire it together with
    the string to the Split String function.
    Rolf Kalbermatter
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

Maybe you are looking for

  • How to use a jdbc query result to redirect to a variable html page

    uh, my problem is that i'm making a servlet which should redirect to a variable html page based on jdbc query (I'm really sorry if this is not the correct forum to post it, but since it's jdbc i thought it was). Anyway, the problem is that when a str

  • SQL--XI--RFC Scenario    MONI Error MAPPING" EXCEPTION_DURING_EXECUTE

    Dear All I am doing Scenario  SQLXIRFC Scenario . I am able to pick the data from sender JDBC Communication Channel . But at SXMB_MONI , i am getting this error   MAPPING">EXCEPTION_DURING_EXECUTE <SAP:Category>Application</SAP:Category>   <SAP:Code

  • RFC call through JCo or webservice

    Can anybody point differences(advantages/disadvantages) between a)calling a BAPI using JCo b)creating a web service for the RFC and calling the webservice fron WD application. regards, Bhupesh

  • Can't access audiobooks

    iI can't find my audiobooks on iTunes. I have read that only one download is allowed. If we are paying full price for the book ( not cheap!) we should be able to access and download as often as we like. Other wise charge a rental similar to movies wi

  • Unable to switch pc to mac

    I have a pc formatted ipod (click-wheel, 20gb 4th generation, w/ USB connector) The iPod is working fine, but the Mac won't recognize it everytime I plug it it, only sometimes; and then when it does and I try to restore it iPod Updater starts restori