如何在Java中实现输入"add 5"累加、"set 5"初始化变量?
How to Implement "add" and "set" Commands in Java
Got it, let's break this down step by step. You need to handle two specific commands: set X (which initializes your stored value to X) and add X (which adds X to the current stored value). Since the function is named maximumProgramValue, we'll also make sure we never let the value drop below 0—because adding a negative number could pull it into negatives, and we want to keep the highest possible value at all times.
Here's the complete, working code that fills in your provided framework:
import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Solution { /* * Complete the maximumProgramValue function below. */ static long maximumProgramValue(int n) { // Start with a default value of 0 long currentValue = 0; for (int i = 0; i < n; i++) { // Grab the command type and the associated number String command = scanner.next(); long number = scanner.nextLong(); if ("set".equals(command)) { // Overwrite the current value with the given number currentValue = number; } else if ("add".equals(command)) { // Add the number, but don't let the value go negative currentValue += number; // If adding makes it negative, reset to 0 to preserve the maximum possible value if (currentValue < 0) { currentValue = 0; } } } return currentValue; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); long result = maximumProgramValue(n); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } }
Key Details Explained:
- Long Data Type: We use
longinstead ofintto avoid integer overflow—critical if you're dealing with large numbers or a high volume ofaddcommands. - Simple Command Parsing: Using
scanner.next()andscanner.nextLong()is cleaner than splitting strings, since the input format is always a command followed by a number. - Non-Negative Guard: The "maximum" in the function name implies we shouldn't hold onto negative values. If an
addwould make the value negative, we reset it to 0—there's no upside to keeping a negative value when we can start fresh from zero. - Main Function Setup: The main method handles input/output as typical in coding challenges—reading the number of commands, executing the logic, and writing the result to the specified output file.
Example Test Case:
If you run with n=4 and these commands:
set 5→ currentValue = 5add 3→ currentValue = 8add -10→ would become -2, so we reset to 0add 7→ currentValue = 7
The final result returned would be 7.
内容的提问来源于stack exchange,提问作者Rupendra Singh
相关产品推荐
相关产品推荐

