//我刚刚开始学java,这是一个计算器的外形,实现了简单的监听,请高手托动到问题处:import java.awt.event.*;
import java.awt.*;class TestCom
{
Frame f=new Frame("计算器!");
Panel p1=new Panel();
Panel p2=new Panel();
TextField tf=new TextField(20);
public TestCom()
{
Button []b=new Button[20];
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}


b[10]=new Button("EXIT");
b[11]=new Button("BACKSPACE");
/*b[12]=new Button("CE");
b[13]=new Button("");
b[14]=new Button("+");
b[15]=new Button("-");
b[16]=new Button("*");
b[17]=new Button("//");
b[19]=new Button("=");
*/

p1.add(tf);
p2.setLayout(new GridLayout(3,4,2,2));
for(int i=0;i<12;i++)
{
b[i].addActionListener(new Num());
p2.add(b[i]);
}
f.setSize(300,150);
f.add(p1,"Center");
f.add(p2,"South");
f.show();
}

public static void main(String[] args)
{
TestCom tc =new TestCom();
}

class Num implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String temp=e.getActionCommand();
if(temp.equals("EXIT"))
System.exit(0);
                           //问题在这里
if(temp.equals("BACKSPACE"))
{
temp=tf.getText();
temp=temp.substring(0,(temp.length())-1);//问题
tf.setText(temp);
if(temp.equals(""))
tf.setText("1");
}
else
tf.setText(tf.getText()+temp);

}
}
}/*
这是一个退格监听,我用了substring方法让tf中的字符从后向前依次减1,
substring(0,(temp.length())-1),可是我觉得(temp.length())-1本身就是字符串的长度,应该是-2才对,但是-2每一次会去掉两个字符,请问这怎么解释呢??谢谢!*/

解决方案 »

  1.   

    substring(..), uses index instead of length, then character pointed by the end index is not included.For example,
    "abc" length is 3. index 2 points to "c". so 
    "abc".substring(0,"abc".length()-1) ===> "abc".substring(0,2) = "ab"
      

  2.   

    substring
    public String substring(int beginIndex,
                            int endIndex)
    Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. 
    ____________________________他已经把endIndex - 1 了!