java - 即使设置了抛出 IllegalArgumentException 也更新对象

标签 java arrays object exception throw

我正在开发一个java程序,我需要在我的主方法中针对gradeItem类执行测试。在我的主要方法中,我有一个用于创建新对象(gradeItem2)的数组:

// Uses string array from input file to create new gradeItem object
public static void processGradeItemData(String[] a) { 

  int int1 = Integer.parseInt(a[2]);
  int int2 = Integer.parseInt(a[7]);
  int int3 = Integer.parseInt(a[8]);

  System.out.println("Running Test 2b:");
  if (a[1].equals("ADD")) {
     GradeItem gradeItem2 = new GradeItem(int1, a[3], a[4], a[5], a[6], int2, int3);
     System.out.println(gradeItem2.toString() + "\n");
  }

} // End processGradeItemData 

在我的 GradeItem 类中,如果输入的信息不是应有的信息,则有很多异常(exception):

public class GradeItem {  

private int gradeItemId;            // Unique ID for each item graded
private String studentId;           // Unique ID for each Student
private String courseId;            // Unique ID for each course
private String itemType;            // Item Type validated with array
private String date;                // Date the item was due
private int maximumScore;           // Maximum points that can be earned
private int actualScore;            // Score of item recieved by student

String[] itemTypeArray = new String[]{"HW", "Quiz", "ClassWork", "Test",
                                        "Final"};

//************************************************************************

  GradeItem() {

  } // end GradeItem

//************************************************************************

  public GradeItem(int gradeItemId, String studentId, String courseId, 
                            String itemType, String date, int maximumScore,
                            int actualScore) {

     if (gradeItemId < 0) {
        throw new IllegalArgumentException("Grade item id cannot be blank");
     }
     if (studentId.equals("")) {
        throw new IllegalArgumentException("Student id cannot be blank");
     }
     if (courseId.equals("")) {
        throw new IllegalArgumentException("Course id cannot be blank");
     }
     if (itemType.equals("")) {
        throw new IllegalArgumentException("Item type cannot be blank");
     }
     for(int i = 0; i <= 4; i++) {
        if(itemTypeArray[i] != itemType) {
           continue;
        }
        if(itemTypeArray[i] == itemType) {
           break;
        }
        throw new IllegalArgumentException("Item type must be valid selection");
     } 
     if (date.equals("")) {
        throw new IllegalArgumentException("Date cannot be blank");
     }
     if (maximumScore < 0) {
        throw new IllegalArgumentException("Maximum score must be greater"
                                           + "than 0");
     }
     if (actualScore < 0 || actualScore > maximumScore) {
        throw new IllegalArgumentException("Actual score must be between"
                                           + "0 and " + maximumScore);
     }

     this.gradeItemId = gradeItemId;
     this.studentId = studentId;
     this.courseId = courseId;
     this.itemType = itemType;
     this.date = date;
     this.maximumScore = maximumScore;
     this.actualScore = actualScore;

  } // end GradeItem

} // end GradeItem

我的问题是,即使我将代码更改为:

,gradeItem2 始终会被创建
     GradeItem gradeItem2 = new GradeItem(int1, a[3], a[4], a[5], a[6], int2, int3);

至:

     GradeItem gradeItem2 = new GradeItem(int1, a[3], a[4], "testing", a[6], int2, int3);

而且我不知道如何更改代码,以便在该值与 itemTypeArray 中的值不匹配时抛出异常:

 for(int i = 0; i <= 4; i++) {
    if(itemTypeArray[i] != itemType) {
       continue;
    }
    if(itemTypeArray[i] == itemType) {
       break;
    }
    throw new IllegalArgumentException("Item type must be valid selection");
 } 

如有任何帮助,我们将不胜感激。谢谢!

更新:

我已经编辑了代码以使用 .equals 而不是 ==,但仍然没有得到期望的结果。如果 itemType 与 itemTypeArray 中列出的任何内容匹配,我尝试更新对象gradeItem2,但如果它经过循环并且与任何 itemTypeArray 值都不匹配,那么它将引发错误。所以看起来我创建的 for 循环有问题。

         for(int i = 0; i <= 4; i++) {
        if(!itemTypeArray[i].equals(itemType)) {
           continue;
        }
        else
        if(itemTypeArray[i].equals(itemType)) {
           break;
        }
        throw new IllegalArgumentException("Item type must be valid selection");
     } 

最佳答案

if(itemTypeArray[i] != itemType) { 不是比较字符串的正确方法。使用 !itemTypeArray[i].equals(itemType)

但即便如此,紧随其后的是 if(itemTypeArray[i] == itemType) { ,即您正在检查 boolean 条件及其补码,其中至少有一个为 true,因此 throw 无法到达。

目前尚不清楚您实际上想通过该循环实现什么目标。涉及 Arrays.asList(itemTypeArray).contains(itemType) 的内容可能会更容易。

例如,如果您只是尝试断言该值在数组中,则可以使用以下代码代替循环:

if (!Arrays.asList(itemTypeArray).contains(itemType)) {
  throw new IllegalArgumentException(...);
}

itemTypeArray 构建为常量 Set 可能是一个更好的选择,因此您不必继续构建此列表;不过,这是一个很小的列表,因此差异可能可以忽略不计。

另一种方法是使用枚举作为项目类型。

关于java - 即使设置了抛出 IllegalArgumentException 也更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52468941/

相关文章:

java - 电报机器人 java : inline url button does not create an update and thus no callback data to respond on

java - 循环遍历字符串来检查值。 (Java计算器)

javascript:对象数组循环

c++ - 将新对象添加到动态数组

java - 在 android.support.design.widget.NavigationView 类中出现错误

java - @ComponentScan 和 @Autowired 无法从特定包注入(inject)

java - 随机无法识别 Maven 依赖项

java - 使用由用户/输入确定的元素创建数组

python - 在 numpy 的二维数组中的特定位置插入一列?

JavaScript 无法设置颜色