You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

计算器Bug:仅输出输入算式而非计算结果求助

Fixing Your Java Calculator Not Producing Expected Results

Let's break down why your calculator isn't working correctly and fix it step by step — there are a few key issues in the code that are causing the unexpected behavior:

Main Issues in the Original Code

  • Scanner is closed too early: When you call reader0.close() after reading the first input, it closes the underlying System.in stream. This means any subsequent Scanners (like reader2) won't be able to read input at all.
  • Incorrect operator capture: Your loop over the input string only keeps the last character in the test variable. So if you enter something like 3+5, test ends up being '5' instead of '+' — that's why your program never triggers the calculation logic.
  • String concatenation instead of numeric calculation: When you do System.out.println(a+c), you're just joining two strings (like "3"+"5" becomes "35"), not adding the numbers.
  • Unused variables and commented-out logic: Variables like b are declared but never used, and most of the calculation code is commented out, so even if the operator was captured, those operations wouldn't run.
  • Incorrect sqrt usage: You're passing the string a to Math.sqrt() instead of the parsed number variable.

Step-by-Step Fixes

  1. Don't close Scanners that use System.in (or use a single Scanner for all input)
    Closing System.in makes it unavailable for future input. It's better to create one Scanner instance and reuse it throughout the program.

  2. Properly capture the operator and split the first number
    Modify the loop to stop when it hits an operator, save that operator, and capture the first number correctly.

  3. Convert input strings to numeric types before calculation
    Use Double.parseDouble() on your input strings to get numeric values you can perform arithmetic with.

  4. Uncomment and fix the calculation logic
    Restore the commented-out code and update it to use the parsed numeric values instead of strings.

Fixed Code

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        // Introduce the calculator
        System.out.println("Welcome to my calculator test");
        System.out.println("Function inputs; + to add numbers, - to subtract numbers, * to multiply, / to divide, ^ to power, # to square root.");

        // Use a single Scanner for all input
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter first number or expression (e.g., 3+ or # for sqrt)");
        String input = scanner.nextLine();

        char operator = ' ';
        StringBuilder firstNumberStr = new StringBuilder();
        boolean operatorFound = false;

        // Parse the input to extract first number and operator
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if ((Character.isDigit(c) || c == '.') && !operatorFound) {
                firstNumberStr.append(c);
            } else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '#' || c == '^') {
                operator = c;
                operatorFound = true;
                // Stop looping once we find the operator (for single-operator expressions)
                break;
            } else {
                System.out.println("Invalid input format. Please try again.");
                scanner.close();
                return;
            }
        }

        // Handle square root case first
        if (operator == '#') {
            try {
                double number = Double.parseDouble(firstNumberStr.toString());
                System.out.println("Square root result: " + Math.sqrt(number));
            } catch (NumberFormatException e) {
                System.out.println("Error: Invalid number for square root.");
            }
        } else if (operator != ' ') {
            // Get second number
            System.out.println("Please enter second number");
            String secondNumberStr = scanner.nextLine();

            try {
                double num1 = Double.parseDouble(firstNumberStr.toString());
                double num2 = Double.parseDouble(secondNumberStr);
                double result = 0;

                switch (operator) {
                    case '+':
                        result = num1 + num2;
                        break;
                    case '-':
                        result = num1 - num2;
                        break;
                    case '*':
                        result = num1 * num2;
                        break;
                    case '/':
                        if (num2 == 0) {
                            System.out.println("Error: Cannot divide by zero.");
                            scanner.close();
                            return;
                        }
                        result = num1 / num2;
                        break;
                    case '^':
                        result = Math.pow(num1, num2);
                        break;
                    default:
                        System.out.println("ERROR: Unknown operator.");
                        scanner.close();
                        return;
                }

                System.out.println("Result: " + num1 + " " + operator + " " + num2 + " = " + result);
            } catch (NumberFormatException e) {
                System.out.println("Error: Invalid number input.");
            }
        } else {
            System.out.println("ERROR: No valid operator found.");
        }

        scanner.close();
    }
}

Key Improvements in the Fixed Code

  • Uses a single Scanner instance and closes it only at the end of the program.
  • Properly parses the input to capture the first number and operator correctly.
  • Adds error handling for invalid numbers, division by zero, and unknown operators.
  • Uses a switch statement for cleaner operator logic instead of multiple else if blocks.
  • Converts all input strings to double before performing arithmetic operations.
  • Provides clear output messages for results and errors.

内容的提问来源于stack exchange,提问作者c.jones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:22:39