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

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 col and row variables 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

  1. Separate Loop Variables: Used i and j instead of reusing col/row—this keeps your original array dimension values intact and avoids logic conflicts.
  2. Fixed Newline Bug: After using scan.nextInt(), we call scan.nextLine() to consume the leftover newline character, which prevents the subsequent nextLine() from reading an empty string.
  3. 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.
  4. Input Validation: Added a check to ensure the user enters the correct number of items, so you don't get array index errors.
  5. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:22:10