如何实现字符串与整数混合输入的加法及值初始化功能?
Fixing the "add" and "set" Operation Handler in Java
Alright, let's get your code working properly for the required operations. First, let's break down the problems in your current code:
- You’re trying to call
next()andnextLong()on aStringvariables—that’s a mistake! Those methods belong to theScannerclass, not plainStringobjects. - The "set" operation logic is completely missing: right now, when you get a "set" command, you just read the value but never update
xwith it. - While the idea of tracking the maximum
xvalue is there, the broken input handling means the core operations won’t run as intended.
Here’s the corrected, working version of your code that handles both commands correctly and tracks the highest value x reaches:
import java.util.Scanner; public class Solution { static long maximumProgramValue(int n) { long x = 0L; long maxValue = 0L; // Renamed for clarity—this tracks the highest x we've seen Scanner scanner = new Scanner(System.in); for (int i = 0; i < n; i++) { // Read the operation first (either "add" or "set") String operation = scanner.next(); // Then read the numeric value associated with the operation long value = scanner.nextLong(); if (operation.equals("add")) { x += value; // Add the value to x } else if (operation.equals("set")) { x = value; // Set x directly to the provided value } // Update our max value if current x is larger than what we've recorded if (x > maxValue) { maxValue = x; } } scanner.close(); // Clean up the scanner resource return maxValue; } public static void main(String[] args) { Scanner inputScanner = new Scanner(System.in); int n = inputScanner.nextInt(); inputScanner.nextLine(); // Consume the leftover newline after reading n long result = maximumProgramValue(n); System.out.println(result); inputScanner.close(); } }
What We Fixed & Why:
- Proper Input Reading: We use the
Scannerdirectly to pull the operation string and numeric value, which fixes the invalid method calls on aString. - "set" Operation Logic: We added the code to set
xto the input value when the command is "set"—that’s the core functionality you were missing. - Clearer Variable Names: Renamed
counttomaxValueso anyone reading the code can immediately tell what it’s for. - Cleaner Loop: Switched from a
whileloop to aforloop since we know exactly how many operations we need to process (n). - Resource Cleanup: Added
close()calls on the scanners to make sure we’re not leaving resources hanging. - Main Method Fix: Handled the newline after reading
nto prevent the first operation read from picking up an empty string.
Now this code will do exactly what you need:
- When you input
add y, it addsyto the current value ofx - When you input
set x, it resetsxto the provided value - It keeps track of the highest value
xever hits and returns that number at the end.
内容的提问来源于stack exchange,提问作者rs dwd
相关产品推荐
相关产品推荐

