Eclipse无法显示多方法输出?Java计算器代码问题咨询
Hey there! Let's work through your calculator project issues and get your code looking sharp, following industry standards.
Why isn't "Enter two numbers to add:" showing up?
The simple answer: you never call the operands() method in your main function! Methods don't run automatically unless you explicitly invoke them. Right now, after the user selects an operation, your code just prints the confirmation and stops—there's no line like operands() to trigger that method's output and input logic.
Also, I noticed you're using newInput.nextLine() but didn't include the Scanner initialization. You'll need to declare a static Scanner instance at the top of your class to avoid errors:
import java.util.Scanner; public class Calculator extends Calculator_Assets { // Add this line to initialize the Scanner private static Scanner newInput = new Scanner(System.in); // ... rest of your code ... }
Fix it by adding a call to operands() inside each branch of your if-else block. For example:
if (word.equals("1")) { System.out.println("You have chosen Addition!"); operands(); // Now this method will run }
Code Structure Optimization & Industry Standards
Let's break down how to make your code cleaner, more maintainable, and aligned with Java best practices:
Keep methods focused on one job
Youroperands()method currently prompts for addition specifically, but it should be flexible for any operation. Rename it to something likegetOperands()and adjust the prompt to match the selected operation. Or better yet, pass the operation name as a parameter:public static void getOperands(String operation) { System.out.println("Enter two numbers to " + operation + ":"); String num1 = newInput.nextLine(); String num2 = newInput.nextLine(); // Convert strings to numbers and perform calculation here }Then call it like
getOperands("add")when the user selects option 1.Avoid redundant print statements
Instead of repeatingSystem.out.printlnfor each menu option, create a single method to print the menu:public static void printMenu() { System.out.println("Choose One!"); System.out.println("1. Addition"); System.out.println("2. Subtraction"); System.out.println("3. Multiplication"); System.out.println("4. Division"); }Then just call
printMenu()inmain—much cleaner!Format code for readability
Always use proper indentation (4 spaces is standard) and curly braces for all control blocks (even single-line if statements). This makes your code easier to read and debug. For example:// Good practice if (word.equals("1")) { System.out.println("You have chosen Addition!"); getOperands("add"); } else if (word.equals("2")) { // ... rest of code ... }Handle input validation and exceptions
Right now, if the user enters a non-number or tries to divide by zero, your program will crash. Add checks:- Convert input strings to
intordoublewith try-catch blocks to handle invalid numbers. - For division, check if the second number is zero before performing the operation.
- Convert input strings to
Limit static method use (when possible)
As you get more comfortable with Java, try using instance methods instead of static ones. This makes your code more object-oriented, which is core to Java's design. For example, create aCalculatorinstance inmainand call methods on it.Clean up resources
Don't forget to close the Scanner when you're done using it to avoid resource leaks:public static void main(String[] args) { // ... your main code ... newInput.close(); }
Example Optimized Code Snippet
Here's a quick revised version incorporating these tips:
import java.util.Scanner; public class Calculator { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { printMenu(); String choice = scanner.nextLine(); switch (choice) { case "1": handleOperation("Addition", (a, b) -> a + b); break; case "2": handleOperation("Subtraction", (a, b) -> a - b); break; case "3": handleOperation("Multiplication", (a, b) -> a * b); break; case "4": handleOperation("Division", (a, b) -> { if (b == 0) throw new ArithmeticException("Cannot divide by zero!"); return a / b; }); break; default: System.out.println("Invalid choice. Please select a number between 1-4."); } scanner.close(); } private static void printMenu() { System.out.println("Choose an operation:"); System.out.println("1. Addition"); System.out.println("2. Subtraction"); System.out.println("3. Multiplication"); System.out.println("4. Division"); } private static void handleOperation(String operationName, java.util.function.DoubleBinaryOperator operation) { System.out.println("You have chosen " + operationName + "!"); System.out.println("Enter two numbers:"); try { double num1 = scanner.nextDouble(); double num2 = scanner.nextDouble(); double result = operation.applyAsDouble(num1, num2); System.out.println("Result: " + num1 + " " + getOperatorSymbol(operationName) + " " + num2 + " = " + result); } catch (java.util.InputMismatchException e) { System.out.println("Error: Please enter valid numbers."); } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } } private static String getOperatorSymbol(String operationName) { return switch (operationName) { case "Addition" -> "+"; case "Subtraction" -> "-"; case "Multiplication" -> "*"; case "Division" -> "/"; default -> ""; }; } }
内容的提问来源于stack exchange,提问作者Chance Lerman

