如何在不使用类的情况下将方法中的输入值传递到另一方法打印?
Alright, let's figure out how to get those test scores from your populateTestScores method over to printStudentReport without using classes. The main issue you're probably hitting is that individual variables in one method can't be directly accessed by another—so we need a way to collect all those scores and pass them as a group.
Here's a straightforward solution using an array to store the scores, which lets us hand off all the input values between methods easily:
Step-by-Step Explanation & Code
First, we'll have populateTestScores collect all the student scores into an array and return that array. Then we'll pass this array to printStudentReport, which can loop through it to print each score and calculate things like the class average (matching the formatted output you're expecting).
import java.util.Scanner; public class StudentScoreReport { public static void main(String[] args) { // Get the array of test scores from the input method int[] studentScores = populateTestScores(); // Pass the array to the report printing method printStudentReport(studentScores); } public static int[] populateTestScores() { Scanner keyboard = new Scanner(System.in); // First, ask how many students we're dealing with System.out.print("Enter number of students: "); int numStudents = keyboard.nextInt(); // Create an array to hold all scores int[] scores = new int[numStudents]; // Loop to collect each student's score for (int i = 0; i < numStudents; i++) { System.out.print("Enter score for student " + (i + 1) + ": "); scores[i] = keyboard.nextInt(); } keyboard.close(); return scores; // Return the full array of scores } public static void printStudentReport(int[] scores) { System.out.println("\n--- Student Test Score Report ---"); int totalScore = 0; // Print each student's score and calculate total for (int i = 0; i < scores.length; i++) { System.out.println("Student " + (i + 1) + ": " + scores[i]); totalScore += scores[i]; } // Calculate and print class average double classAverage = (double) totalScore / scores.length; System.out.printf("Class Average: %.2f%n", classAverage); } }
Why This Works
Instead of trying to pass a single stuScore variable (which only holds one value at a time), we use an array to store all the scores collected in populateTestScores. When we return this array from the method, we can pass it directly to printStudentReport, which has full access to every score in the array.
This approach keeps things simple without needing classes, and it will produce the structured report you're looking for—with individual student scores and a formatted class average.
内容的提问来源于stack exchange,提问作者Ponoco-nuchi

