如何将测试类中的字符串输入改为Scanner输入并应用到代码中
Got it, let's walk through how to modify your test class to use Scanner for user input instead of the hardcoded string. Here's a straightforward breakdown:
Step 1: Import the Scanner class
First, you need to add an import statement at the top of your file to access Java's built-in Scanner utility:
import java.util.Scanner;
Step 2: Rewrite the main method to handle user input
Instead of passing a fixed name to showCustomerInfo, we'll create a Scanner instance, prompt the user for input, capture their entry, and then pass that value to the method.
Modified Full Code
import java.util.Scanner; public class FinancialCalculatorTester { public static void main(String[] args) { // Initialize Scanner to read input from the console Scanner scanner = new Scanner(System.in); // Prompt the user to enter a customer name System.out.print("Please enter the customer's full name: "); String customerName = scanner.nextLine(); // Captures the entire line (including spaces) // Pass the input name to your existing method FinancialCalculator.showCustomerInfo(customerName); // Clean up the Scanner to avoid resource leaks scanner.close(); } }
Key Notes for This Change
scanner.nextLine(): Use this method instead ofscanner.next()because it captures the full input line (including spaces, which is essential for names like "Antonio Williams").next()would stop reading at the first space, only capturing "Antonio" in your example.- User Prompt: The
System.out.print()line gives clear guidance to the user, making the program intuitive to use. - Closing the Scanner: Always call
scanner.close()when you're done with input handling to free up system resources.
What Happens When You Run It?
When you execute the modified code, you'll see this prompt in the console:
Please enter the customer's full name:
After you type a name (e.g., "Antonio Williams") and press enter, the program will output the same customer details as before—but now using the name you entered instead of the hardcoded value.
内容的提问来源于stack exchange,提问作者Lily Barton

