digrev
digrev

Reputation: 97

LastIndexOf function usage

I am trying to learn how to use lastIndexOf function, but the code doesn't work for me. After clicked the button, I just get the whole text, not only the extension. What am I doing wrong?

private  String getExtension(String s)
{
    char dot='.';
    int pos=s.lastIndexOf("dot");
    String root=s.substring(pos+1);
    return root;   
}


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
{               
    String s=jTextField1.getText();
    jLabel1.setText(getExtension(s));
}  

Upvotes: 0

Views: 239

Answers (2)

christopher
christopher

Reputation: 27346

Your problem

You need to remove the quotation marks around the variable name.

int pos=s.lastIndexOf("dot");

becomes

int pos=s.lastIndexOf(dot);

Just an aside

This could have been worked out, VERY easily by yourself if you'd used a debugger. I can't help but feel you've used SO as a first resort, rather than what it should be; a place to go when you've really exhausted all methods of investigation that you are personally aware of.

A debugger

Almost every single IDE (Eclipse, Netbeans etc) have something called a debugger. A debugger allows you to go through your program line by line, and see the value of every single variable as the program develops. If you're using Eclipse, on the toolbar along the top, select Run -> Debug, to initialize the program in debugging mode. For Netbeans, there is a debug button on the right of the Run button (The play symbol). Just a few examples.

Upvotes: 4

syb0rg
syb0rg

Reputation: 8247

Take out the quotes in your lastIndexOf statement.

int pos=s.lastIndexOf("dot");
//                    ^---^
//                      +---------- Take those " out

Upvotes: 1

Related Questions