0

我正在尝试学习如何使用lastIndexOf函数,但代码对我不起作用。单击按钮后,我只得到整个文本,而不仅仅是扩展名。我究竟做错了什么?

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));
}  
4

2 回答 2

4

你的问题

您需要删除变量名称周围的引号。

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

变成

int pos=s.lastIndexOf(dot);

只是旁白

如果您使用调试器,这可以很容易地由您自己解决。我不禁觉得您已将 SO 用作第一选择,而不是应有的选择;当您真的用尽了您个人知道的所有调查方法时,可以去的地方。

调试器

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.

于 2013-04-07T19:31:34.383 回答
1

Take out the quotes in your lastIndexOf statement.

int pos=s.lastIndexOf("dot");
//                    ^---^
//                      +---------- Take those " out
于 2013-04-07T19:31:41.603 回答