Java接收用户输入存入二维数组时遇问题,寻求解决方案
Fixing Your 2D Array Input for Student Data
Hey there! I see where you're running into trouble with your code. Let's break down the issues and fix them step by step.
Key Problems in Your Current Code
- You're reusing the
colandrowvariables as loop counters, which overwrites the original values you set for the array dimensions. This will mess up your array logic entirely. - The input prompt asks for "name and grades" but
scan.next()only reads a single token (up to the first space). So if a student's name has a space (like "Jane Smith") or you try to enter multiple grades at once, it won't capture the data correctly. - You're prompting the user for input every time you iterate over a row element, which is confusing—users expect to enter all info for one student at once, not piecemeal.
Corrected Code
Here's a revised version that fixes these issues and makes the input flow intuitive:
import java.util.Scanner; public class StudentGrades { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("How many students? "); int numStudents = scan.nextInt(); // Consume the leftover newline after nextInt() to avoid empty input bugs scan.nextLine(); // Each student has 5 entries: 1 name + 4 grades (matches your row=5 setup) int entriesPerStudent = 5; String[][] studentData = new String[numStudents][entriesPerStudent]; for (int i = 0; i < numStudents; i++) { int studentNumber = i + 1; System.out.printf("Enter name and 4 grades for student %d (separate with spaces): %n", studentNumber); // Read the entire input line and split into individual values String[] inputTokens = scan.nextLine().split(" "); // Basic validation to ensure correct input count if (inputTokens.length != entriesPerStudent) { System.out.println("Oops! Please enter exactly 1 name + 4 grades. Try again."); i--; // Go back to re-enter data for this student continue; } // Copy the split values into the 2D array for (int j = 0; j < entriesPerStudent; j++) { studentData[i][j] = inputTokens[j]; } } // Print the stored data to verify it works System.out.println("\nStored Student Data:"); for (int i = 0; i < numStudents; i++) { System.out.printf("Student %d: ", i + 1); for (String entry : studentData[i]) { System.out.print(entry + " "); } System.out.println(); } scan.close(); } }
What Changed & Why
- Separate Loop Variables: Used
iandjinstead of reusingcol/row—this keeps your original array dimension values intact and avoids logic conflicts. - Fixed Newline Bug: After using
scan.nextInt(), we callscan.nextLine()to consume the leftover newline character, which prevents the subsequentnextLine()from reading an empty string. - Single Prompt Per Student: Users enter all info for one student in a single line, which is more intuitive. We split the input into tokens to fill the array row.
- Input Validation: Added a check to ensure the user enters the correct number of items, so you don't get array index errors.
- Verification Print: Added a loop to print out the stored data so you can confirm it's working as expected.
Alternative: Step-by-Step Input
If you prefer to prompt for each piece of info individually (like name, then each grade), here's a more guided version:
import java.util.Scanner; public class StudentGradesAlt { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("How many students? "); int numStudents = scan.nextInt(); int entriesPerStudent = 5; String[][] studentData = new String[numStudents][entriesPerStudent]; for (int i = 0; i < numStudents; i++) { int studentNumber = i + 1; System.out.printf("\nEnter details for student %d:%n", studentNumber); // Prompt for name System.out.print("Student Name: "); studentData[i][0] = scan.next(); // Prompt for each grade for (int j = 1; j < entriesPerStudent; j++) { System.out.printf("Grade %d: ", j); studentData[i][j] = scan.next(); } } // Print verification System.out.println("\nStored Student Data:"); for (int i = 0; i < numStudents; i++) { System.out.printf("Student %d: %s%n", i + 1, String.join(" ", studentData[i])); } scan.close(); } }
This version is more verbose but guides the user through each input step, which might be clearer if you're just starting out with arrays.
内容的提问来源于stack exchange,提问作者Aaron Larson
相关产品推荐
相关产品推荐

