有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java跟踪最高数组元素

/** (B) declare and create an array to contain at least 100 records */
    String arrayRec[] = new String[100];
/** (B) manually populate a few records ... use supplemental file provided */
    arrayRec[0] = "FirstValue";
    arrayRec[1] = "SecondValue";
    arrayRec[2] = "ThirdValue";
    arrayRec[3] = "FourthValue";
    arrayRec[4] = "FifthValue";
    arrayRec[5] = "SixthValue";
    arrayRec[6] = "SeventhValue";
    arrayRec[7] = "EigthValue";
    arrayRec[8] = "NinthValue";
    arrayRec[9] = "TenthValue";
    /** (B) declare and initialize and integer variable, imax to track the highest array element used (9) */

谁能告诉我初始化变量int iMax以“跟踪”使用的最高数组元素(9)的方向是什么意思? 我不太明白


共 (1) 个答案

  1. # 1 楼答案

    在这种情况下,数组中的“最高”或最后一个元素是“TenthValue”

    也就是说,您有一个由十个字符串组成的数组(数组中0被计为1),因此iMax变量在向数组中添加索引时保留数组中最后一个元素的记录

    有关数组的更多信息,请查看here

    ***(B)声明并创建一个数组,以包含至少100条记录/ 本部分要求您拥有一个至少包含100条记录的数组,以您的示例为例,您的数组的初始容量仅为10

    String arrayRec[] = new String[10];
    

    应该是:

    String arrayRec[] = new String[100];
    

    作为将来的参考ArrayList会更好地解决这个问题,但我想这是一个初学者的家庭作业

    最新更新

    我刚刚意识到你的问题是什么

    基本上,您需要创建一个大小为100的数组,但不需要填充所有数组,只需要几个索引

    要执行此操作,请使用以下代码:

    //Create the variable which will hold the last element in the array
    int iMax = 0;
    String arrayRec[] = new String[100];
    
    arrayRec[0] = "FirstValue";
    arrayRec[1] = "SecondValue";
    arrayRec[2] = "ThirdValue";
    arrayRec[3] = "FourthValue";
    arrayRec[4] = "FifthValue";
    arrayRec[5] = "SixthValue";
    arrayRec[6] = "SeventhValue";
    arrayRec[7] = "EigthValue";
    arrayRec[8] = "NinthValue";
    arrayRec[9] = "TenthValue";
    
    //Run through each index in the array to see how many are filled
    //All unfilled indexes will be pre filled with null values
    for( String s : arrayRec )
    {
        if( s != null ) //if the index does not contain null
        {
            iMax++; //Add another one to the counter
        }
    }
    
    System.out.println("Highest element in array = " + iMax); //iMax variable will return ten for the ten values