Android计算器小数点功能异常求助:重复输入引发NaN值问题
Hey there! Let's sort out that annoying duplicate decimal point issue you're facing—totally normal for someone new to app development, so don't stress about it.
What's Causing the Problem?
Looking at your current code, the issue is that every time you tap the decimal button, you're always adding a decimal point without checking if one already exists. The try block tries to parse the current text to a double first (which works even if there's already a decimal), but then you immediately append another "."—that's why you end up with strings like "1.2." or "1..2" later on, which can't be parsed to a number (hence the NaN errors).
The Fix
We need to add simple checks before adding the decimal point. Here's how to adjust your code:
b_dot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String currentDisplay = show.getText().toString(); // If the display is empty, start with "0." instead of just "." if (currentDisplay.isEmpty()) { show.setText("0."); } // Only add a decimal if there isn't one already else if (!currentDisplay.contains(".")) { show.setText(currentDisplay + "."); } // Do nothing if a decimal already exists—no more duplicates! } });
Why This Works
- Empty display check: Prevents users from entering a standalone "." (which would cause parsing errors later). Instead, we start with "0." which is a valid partial number.
- Duplicate decimal check: Using
contains(".")ensures we only add a decimal point if the current number doesn't have one already. This eliminates those invalid double-decimal strings entirely.
You can also remove that try-catch block from the decimal button click handler now—since we're preventing invalid inputs before they happen, there's no need to handle parsing exceptions here anymore.
内容的提问来源于stack exchange,提问作者Chris

