首页 > 解决方案 > 子字符串删除 2 个字符而不是 1 个

问题描述

我的任务要求我有这个清除最后一个按钮,它可以删除字符串中的最后一个字符。从代码中可以看出,它应该排除最后一个数字。

问题是当我在输入数字后第一次按下它时,它会删除 2 并且后续使用会删除 1。知道如何解决这个问题吗?

代码:

case "Clear Last":
    String remove;
    remove = text.substring(text.length()-1);
    switch (remove) {
        case "+":
            add = false;
            text = text.substring(0, text.length() - 1);                    
            display.setText(text);
            break;
        case "-":
            subtract = false;
            text = text.substring(0, text.length() - 1);                    
            display.setText(text);
            break;
        case "*":
            multiply = false;
            text = text.substring(0, text.length() - 1);                    
            display.setText(text);
            break;
        case "/":
            divide = false;
            text = text.substring(0, text.length() - 1);                    
            display.setText(text);
            break;
        default:
                text = text.substring(0, text.length()-1);
                display.setText(text);
            break;
    }
    break;

示例输出:

77777 -> 清除最后一个 -> 777 -> 清除最后一个 -> 77 -> 778888 -> 清除最后一个 -> 7788 -> 清除最后一个 -> 778

标签: javastringswitch-statementsubstring

解决方案


问题在这里(以及所有这些片段): -

text = display.getText();
display.setText(text + "7");

在更新. text _ display您应该互换它们,它应该可以工作:-

display.setText(text + "7");
text = display.getText();

更好的是,只需更新text和设置displayoutside的值switch,如下所示:-

public void actionPerformed(ActionEvent e) {
    switch (e.getActionCommand()) {
        case "1":
        case "2":
        case "3":
        case "4":
        case "5":
        case "6":
        case "7":
        case "8":
        case "9":
        case "0":
        case ".":
            text += e.getActionCommand();
            break;
        case "=":
            break;
        case "Clear Last":
            text = text.substring(0, (text.length() - 1));
            break;
        case "Clear All":
            text = "";
            break;
        default:
            text = "";
            break;
    }
    display.setText(text);
}

或者通过摆脱 switch-case 来进一步改进它 - 检查是否e.getActionCommand()是数字,然后执行text += e.getActionCommand();,否则如果....


推荐阅读