簡體   English   中英

如果超出范圍,則返回空字符串

[英]Return empty string if out of bounds

如果輸入了超出范圍的數字,我如何讓我的程序返回一個空集? 底部的課程僅是測試人員,因此如果有人將Jezebel更改為第7行,我如何避免它崩潰? 由於只有六行。

import java.util.Arrays;

public class Classroom {

private String[][] desks;
private String[] students = {"Todd", "Harry", "James", "Bob", "Michael",
    "Fred", "Andy", "Jessica", "Kara", "Ed", "Jane", "", "Dennis", "Dwight",
    "Sandy", "", "Toby", "", "Sara", "", "Randy", "", "", "", "", "John", "",
    "", "", "Lindsay", "", "", "", "", "", "Marie", "", "", "", "",
    "David", "", "",};

// the number of row is desks.length
// the number of column is desks[0].length 
public Classroom(int row, int column) {
    int i = 0;
    desks = new String[row][column];

    for (int r = 0; r < row; r++) {
        for (int c = 0; c < column; c++) {
            desks[r][c] = students[i++];
            //Arrays.fill(desks[r][c], students[i++]);
        }
    }
}

public void setDesks(String[][] desks) {
    this.desks = desks;
}

public boolean isDeskTaken(int row, int column) {
    boolean taken = false;
    if (desks[row][column] == "") {
        taken = true;
    }
    if (desks[row][column].isEmpty()) {
        taken = false;
    }
    return taken;
}

public String getRow(int row) {
    String name = Arrays.toString(desks[row]);
    return name;
}

public String getStudent(int row, int column) {
    return desks[row][column];
}

public boolean placeStudent(int row, int column, String name) {
    boolean placed = false;

    // call isDeskTaken(row, column) if not
    if (desks[row][column].isEmpty()) {
        desks[row][column] = name;
        return true;
    }
    return placed;
} // places student if the seat is empty

public static void main(String[] args) {
    Classroom classroom = new Classroom(6, 5);

    System.out.println("getRow(2)" + classroom.getRow(2));
    System.out.println("placeStudent(7,1) " + classroom.placeStudent(7, 1, "Jezebel"));
    System.out.println("placeStudent(4,0) " + classroom.placeStudent(4, 0, "John"));
    System.out.println("Student " + classroom.getStudent(4, 1) + " has been placed in the 4th row and 1st column");
}

}

您可以在嘗試對數組進行索引之前檢查其長度,如下所示:

String[] myArray = new String[5]; // an array with indexes [0] to [4]

// ...

// at some point we might try to access the element at index [5]
// remembering that we only have indexes [0] -> [4] in a 5 element array
// so we first check that the array is of sufficient length

if(myArray.length >= 6) {
    return myArray[5]; // 6th element
} else {
    return "";
}

再次重申,數組的長度為5個元素,但這些元素的索引為0、1、2、3、4。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM