如何利用循环实现用户输入的读取、求和及结果输出?
Fixing Your Java Input Sum Program
Let's break down what's going wrong in your code first, then build the correct version to read 3 inputs, sum them, and output the total.
Issues in Your Current Code
- Local Variable Scope: You declared
float numinside the firstforloop. That means this variable only exists inside that loop iteration—once the loop finishes, you can't access it at all, let alone use it as an array later. - No Array for Storage: You tried to use
num[i]like an array, butnumis just a single float variable, not an array. You didn't initialize any array to store the 3 input values. - Missing Sum Logic: Your code doesn't actually calculate the sum of the inputs—you were trying to print the values instead of adding them up.
- Incorrect Prompt: Your prompt says "Enter raduis" (typo: should be "radius") which doesn't match your goal of reading generic numbers for summation.
Correct Implementation
Here's a working version that does exactly what you need:
import java.util.Scanner; public class Basic { // Class names should follow PascalCase in Java public static void main(String[] args) { Scanner sc = new Scanner(System.in); float totalSum = 0.0f; // Variable to hold the cumulative sum // Loop 3 times to get inputs and add to sum for (int i = 0; i < 3; i++) { // Use i < 3 instead of i <=2 for clarity System.out.printf("Enter number %d: ", i + 1); // Clear prompt for each input float num = sc.nextFloat(); totalSum += num; // Add each input to the total sum } // Output the final sum System.out.println("The total sum is: " + totalSum); sc.close(); // Good practice to close the scanner } }
How This Works
- Sum Variable: We initialize
totalSumto 0.0f to start with a clean slate for our addition. - Loop for Inputs: The loop runs 3 times (from 0 to 2, since
i < 3). For each iteration, we ask the user for a number, read it, and add it directly tototalSum—no need to store all 3 numbers unless you need them later! - Clear Prompts: Using
printflets us show which number the user is entering (1st, 2nd, 3rd) for better user experience. - Cleanup: We close the
Scannerat the end to free up resources—it's a good habit to get into.
Alternative: Storing Inputs First (If Needed)
If you do need to keep track of each individual input value (not just sum them), you can use an array:
import java.util.Scanner; public class Basic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); float[] numbers = new float[3]; // Array to store 3 floats float totalSum = 0.0f; // Read inputs into array for (int i = 0; i < numbers.length; i++) { System.out.printf("Enter number %d: ", i + 1); numbers[i] = sc.nextFloat(); totalSum += numbers[i]; // Add to sum as we go } // Optional: Print all inputs System.out.println("You entered:"); for (float num : numbers) { System.out.println(num); } System.out.println("The total sum is: " + totalSum); sc.close(); } }
This way you have both the individual values stored and the total sum calculated.
内容的提问来源于stack exchange,提问作者shivam shukla
相关产品推荐
相关产品推荐

