java - 子字符串删除 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
解决方案
问题在这里(以及所有这些片段): -
text = display.getText();
display.setText(text + "7");
在更新. text
_ display
您应该互换它们,它应该可以工作:-
display.setText(text + "7");
text = display.getText();
更好的是,只需更新text
和设置display
outside的值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();
,否则如果....
推荐阅读
- ios - 需要帮助在 Swift 中按时间戳对结构进行排序
- c# - 使用带有多个标签的 GetElementsByTagName
- java - 使用 JAXB 将具有单个变量的 Java 对象转换为 XML
- javascript - 如何将更新的数组对象从reactJs中的子组件传递给父组件
- javascript - 如何在此代码中添加 (+/-) 按钮编号增量器
- c - 向结构 C/C++ 添加另一个变量时出现 Malloc 错误
- javascript - 如何突出显示与结果匹配的表行
- python - 将包含列表列表的 Python Dict 转换为 pandas Dataframe
- c++ - 你怎么能定义一些东西而不给它任何类型,比如整数?
- c# - 如何一次性在内存集合中与其后备数据库表同步