You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用循环实现用户输入的读取、求和及结果输出?

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 num inside the first for loop. 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, but num is 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

  1. Sum Variable: We initialize totalSum to 0.0f to start with a clean slate for our addition.
  2. 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 to totalSum—no need to store all 3 numbers unless you need them later!
  3. Clear Prompts: Using printf lets us show which number the user is entering (1st, 2nd, 3rd) for better user experience.
  4. Cleanup: We close the Scanner at 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:42:37