【问题标题】:Remove the last digit from a String从字符串中删除最后一个数字
【发布时间】:2019-12-30 17:53:39
【问题描述】:

我正在一个 Android XML 应用程序中创建一个 Java 计算器(仅按钮 - 像 T9 键),我想修复“取消”按钮。

当我单击它时,我想取消仅包含数字的字符串中的最后一个数字(或“.”,因为您也可以添加“.”来写入十进制数字)。 有一个问题:如果用户写了一个 int 数(34),我把它转换成 double,它就变成了 34.0,如果我取消最后一位,它就取消了 0。

我也试过String.substring(start,end),但它不起作用...... 您对取消句柄有什么建议吗?谢谢!

这是取消最后一位数字的函数。

/* tv -> TextView
- tvResult contains what the user writes and the result when he clicks "=", - tvCalc contains the calc that the user is entering.
For example, if the user writes with the 0-9 buttons and the operator of the operations, in tvCalc there will be "34+50=", and in tvResult "84" */

public void handleCancel(View v) {
    //tv -> TextView, tvResult contains what the user writes and the result when he clicks "=", tvCalc contains the calc that the user is entering: for example if user writes with the 0-9 buttons and the operator of the operations, in tvCalc there will be "34+50=", and in tvResult "84"

    if (tvResult.length() == 0) {
        errorToast = Toast.makeText(MainActivity.this, "Error! There's nothing to cancel!", Toast.LENGTH_LONG);
        errorToast.show();
    } else {
        tvResult.setText(tvResult.toString().substring(0, tvResult.toString().length() - 1))

        if (tvCalc.toString().contains("=")) {
            tvCalc.setText(tvResult.toString());
            operand1 = tvResult.toString();
        } else {
            tvCalc.setText(tvCalc.toString().substring(0, tvCalc.toString().length() - 1));
            if (operator == "") operand1 = tvResult.toString();
            else {
                operand2 = tvResult.toString();
                try {
                    int conv = Integer.parseInt(tvCalcolo.toString());
                    operazione = "";
                } catch(Exception e) {}
            }
        }
    }
}

添加用户选择的功能:

public void userChoice(View v)
{
    Button clicked=(Button)findViewById(v.getId());
    String choice=clicked.getText().toString();
    try
    {
        int number=Integer.parseInt(choice);
        if (operator=="") 
        {
            operand1+=choice;
            if (tvCalc.toString().contains("=")) tvCalc.setText(operand1);
        } else operand2+=choice;
    } catch (Exception e)
    {
        if (choice.equals('.'))
        {
            if (operator=="") operand1+=choice;
            else operand2+=choice;
        } else 
        {
            if (operand2!="")
            {
                handleEqual(v);
                operand1=tvResult.toString();
            }
            operator=choice;
            tvCalc.append(operator);
            tvResult.setText("");
            return;
        }
    }

    tvCalc.append(choice);
    tvResult.append(choice);
}

感谢 Cardinal System,我编辑了函数“handleCancel”:

public void handleCancel (View v)
{

    double d;
    try
    {
        d=Double.parseDouble(tvRisultato.toString());
    } catch (Exception e)
    {
        bCanc.setText("Error"); //It's the button 'Cancel'
    }

    String newVal;
    if (d%1==0) 
    {
        int val=(int)d;
        newVal=String.valueOf(val);
        newVal=newVal.substring(0,newVal.length()-1);
    } else 
    { 
        newVal=String.valueOf(d);
        newVal=newVal.substring(0,newVal.length()-1);
        if (newVal.endsWith(".")) 
        { 
            newVal=newVal.substring(0,newVal.length()-1);
        }
    }

    tvResult.setText(newVal);

    if ((tvCalc.toString().contains("+")||tvCalc.toString().contains("-")||tvCalc.toString().contains("*")||tvCalc.toString().contains("/")||tvCalc.toString().contains("^"))&&tvCalc.toString().contains("="))
    {
        tvCalc.setText(tvResult.toString());
        operand1=tvResult.toString();
    } else if ((tvCalc.toString().contains("+")||tvCalc.toString().contains("-")||tvCalc.toString().contains("*")||tvCalc.toString().contains("/")||tvCalc.toString().contains("^"))&&!tvCalc.toString().contains("="))
    {
        if (tvCalc.toString().endsWith("+")||tvCalc.toString().endsWith("-")||tvCalc.toString().endsWith("*")||tvCalc.toString().endsWith("/")||tvCalc.toString().endsWith("^")) operator="";
        tvCalc.setText(tvCalc.toString().substring(0,tvCalc.toString().length()-1));
    }
}

【问题讨论】:

  • 请发布您的代码。
  • 如果用户自己没有添加小数点,那么在选择 = 按钮之前也不要以编程方式添加它。 取消应始终与用户实际输入的内容相反,否则需要更多代码。
  • tvResult 是 TextView 吗?
  • 是的,tvResult 是一个 TextView

标签: java string substring calculator


【解决方案1】:

看看这对你有没有帮助:

// Let's make it a double so we have something to work with.
double d = Double.parseDouble(tvResult.getText().toString());

String newText;
if (d % 1 == 0) { // See if the number is a whole number
    int i = (int) d; // If it is, cast it to an int to get rid of the decimal
    newText = String.valueOf(i); // Parse it to a string so we can clip off the end
    newText = newText.substring(0, newText.length() - 1); // Clip off the end
} else { 
    // If it's not a whole number, just parse it to a string.
    newText = String.valueOf(d);
    newText = newText.substring(0, newText.length() - 1); // Clip off the end
    if (newText.endsWith(".")) { 
        // If the number we clipped off was a tenth, clip off the decimal
        newText = newText.substring(0, newText.length() - 1);
    }
}

tvResult.setText(newText);

【讨论】:

  • 嗨!我在我的项目中添加了您的代码,但这里有一个错误:double d = Double.parseDouble(tvResult.toString()); 我添加了一个 try-catch,我查看了tvResult.toString(),它说android.widget.TextView{... 和很多数字,所以在字符串中不仅有用户写入,但这个 id(我认为),我不能将它转换为双精度。我可以做些什么来拆分这个字符串或只取我感兴趣的部分?
  • 嘿!有什么想法吗?
  • @coder999 我需要查看完整的错误消息才能确切了解问题所在。
  • 首先我添加了新handleCancel的代码。当我删除字符串中的最后一个字符时,我没有收到任何错误,但是当有 try-catch 时,它会转到 bCanc.setText("Error");,当它查看 tvCalc 的字符串的内容时,我看到 "android.widget.TextView{42284730 V.ED.... .........0,8-432,53#7f080003 app:id/tvCalc*the number I input*" 怎么能我只使用我输入的数字?
  • @coder999 我更新了我的答案。不要使用TextView#toString(),使用TextView.getText().toString();
【解决方案2】:

看起来您至少可以通过两种方式满足您的要求:

  1. 要删除的模式搜索符号(类似于 (.0|\d|+|-|*|/) ) - 不推荐
  2. 在添加新数字/操作之前记住最后一个输入字符串。 F.e.上按钮。按下您会记住您当前对计算器的输入到变量,如果您需要取消,您只需将当前输入行设置为该变量

希望我的建议对您有所帮助。

【讨论】:

  • 感谢您的回答。当用户单击数字或运算符时,我使用 .append() 添加他的选择
  • @coder999 是的,在调用 append 之前,您还可以在计算器中保存整个输入字符串(由于字符串的不可变性质)您是否还可以使用部分代码更新您的问题,是吗?向字符串添加符号?
  • @coder999 看到,在此方法之前(在按钮声明之前),您可以通过调用 tvCalc.getText().toString() 并将其保存到 class'es 变量来保存应用程序的当前状态。对可能在此方法中更改的其他变量执行相同操作。这样,您的取消操作将始终保证返回到以前的状态。之后,通过这种方式,您可以将内存变量移动到另一个类中,将更改放入有限大小的堆栈中,并且可以在没有应用程序错误的情况下多次取消内存。现在在取消方法中,您只需调用 tvCalc.setText
猜你喜欢
  • 2017-08-19
  • 2011-01-19
  • 2021-12-11
  • 2010-11-08
  • 2011-11-18
  • 2011-08-01
相关资源
最近更新 更多