首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >找不到符号-超出界限错误

找不到符号-超出界限错误
EN

Stack Overflow用户
提问于 2013-07-17 05:47:31
回答 2查看 164关注 0票数 0

我在做一个班级作业。基本上,我们必须使用一维数组来显示学生的姓名、当前成绩和科目。代码如下:

代码语言:javascript
运行
复制
import java.util.*;
import java.util.Arrays;

public class sortStudents {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of students: ");
        int numofstudents = input.nextInt();
        String[] names = new String[numofstudents];
        int[] array = new int[numofstudents];
        String[] subject = new String[numofstudents];
        for(int i = 0; i < numofstudents; i++) {
            System.out.print("Enter the student's name: ");
            names[i] = input.next();
            System.out.print("Enter the student's score: ");
            array[i] = input.nextInt();
            System.out.print("Enter the subject: ");
            subject[i] = input.next();
        }
        selectionSort(names, array, subject);
        System.out.println(names[i] + array[i] + subject[i]);

    }
    public static void selectionSort(String[] names, int[] array, String[] subject) {
        for(int i = array.length - 1; i >= 1; i--) {
            String temp;
            String classTemp = " ";
            int currentMax = array[0];
            int currentMaxIndex = 0;
            for(int j = 1; j <= i; j++) {
                if (currentMax > array[j]) {
                    currentMax = array[j];
                    currentMaxIndex = j;
                }
            }       
                if (currentMaxIndex != i) {
                    temp = names[currentMaxIndex];
                    names[currentMaxIndex] = names[i];
                    names[i] = temp;
                    array[currentMaxIndex] = array[i];
                    array[i] = currentMax;
                    subject[currentMaxIndex] = subject[i];
                    subject[i] = classTemp;
                }
        }       
    }
}

在第22行编译时产生错误。我认为这是由于变量"i“没有在循环外初始化。但是当我把变量"i“放在循环之外时,我得到了一个数组越界错误。如果能帮助我们解决这个问题,我们将不胜感激:)

附言:我是新来这个网站的,所以如果我发错了帖子,我向你道歉。

EN

回答 2

Stack Overflow用户

发布于 2013-07-17 05:55:50

执行此操作时:

代码语言:javascript
运行
复制
System.out.println(names[i] + array[i] + subject[i]);

i变量不存在,因为它直接位于for循环之后,而for循环确实存在。

你可以做的就是在它周围添加另一个for循环:

代码语言:javascript
运行
复制
for(int p =0; p < numOfStudents; p++)
{
 System.out.println(names[p] + array[p] + subject[p]);
}
票数 0
EN

Stack Overflow用户

发布于 2013-07-17 05:55:00

当您到达System.out.println(names[i] + array[i] + subject[i]);时,作用域中没有i变量。

  1. 如果您试图在每次输入信息时打印该信息,请将该代码放入现有的for循环中。
  2. 如果您试图打印最后的排序列表,则需要使用另一个变量创建另一个for循环来遍历数组。

for(int j= 0;j< numOfStudents;j++) {System.out.println(i+ arrayi + subjecti);}

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17687600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档