避免向数组添加 null 值

Avoid Adding Null Value to Array

提问人:yasakrami 提问时间:11/29/2022 最后编辑:HariHaravelanyasakrami 更新时间:11/30/2022 访问量:143

问:

我正在制作一个函数,该函数获取学生的 ID、分数、姓氏和名字,并根据他们的分数、姓氏和名字进行比较,并以降序格式打印结果。

我使用比较器来比较数组的元素。问题是,当用户输入 as 或 时,程序需要中断并显示结果,但是当我使用 break 时,它会向我的数组添加一个 null 值,从而阻止比较。-1scoreID

这是我的代码:

import java.util.Arrays;
import java.util.Scanner;
import java.util.*;

public class Main {
    private static class Student {
        String fName;
        String lName;
        int id;
        int score;

        public Student(String fName, String lName, int id, int score) {
            this.fName = fName;
            this.lName = lName;
            this.id = id;
            this.score = score;
        }

        public int getScore() {
            return score;
        }

        public String getFirstName() {
            return fName;
        }

        public String getLastName() {
            return lName;
        }

        public int getId() {
            return id;
        }

        @Override
        public String toString() {
            return "id: " + this.id + " " + "fName: " + this.fName + " " + "lName: " + this.lName + " " + "score: " + this.score;
        }

    }

    public static boolean alphabetic(String str) {
        char[] charArray = str.toCharArray();
        for (char c : charArray) {
            if (!Character.isLetter(c)) {
                if (c != ' ') {
                    return false;
                }
            }

        }
        return true;
    }

    static class Comparators implements Comparator<Student> {
        @Override
        public int compare(Student s1, Student s2) {
            int n = Integer.compare(s2.getScore(), s1.getScore());
            if (n == 0) {
                int last = s1.getLastName().compareTo(s2.getLastName());
                return last == 0 ? s1.getFirstName().compareTo(s2.getFirstName()) : last;

            } else {
                return n;
            }

        }
    }

    public static void main(String[] args) {
        System.out.println("Enter the number of students");
        Scanner input = new Scanner(System.in);
        HashSet<Integer> used = new HashSet<>();
        List<List<Object>> listData = new ArrayList<List<Object>>();
        int k = input.nextInt();
        Student[] students = new Student[k];
        for (int i = 0; i < k; ) {
            System.out.println("Enter id");
            int id = input.nextInt();
            if (id == -1) {
                break;
            }
            input.nextLine();
            System.out.println("Enter first name ");
            String fName;
            while (alphabetic(fName = input.nextLine()) == false) {
                System.out.println("Wrong! please enter again");
            }
            fName = fName.replace(" ", "");
            System.out.println("Enter last name ");
            String lName;
            while (alphabetic(lName = input.nextLine()) == false) {
                System.out.println("Wrong! please enter again");
            }
            lName = lName.replace(" ", "");
            System.out.println("Enter score ");
            int score = input.nextInt();
            if (score == -1) {
                break;
            }
            if (used.contains(id)) {
                listData.add(Arrays.asList(id, lName, fName, score));
                continue;
            }
            used.add(id);
            students[i++] = new Student(fName, lName, id, score);

        }
        Arrays.toString(students);
        System.out.println(Arrays.toString(students));
        Arrays.sort(students, new Comparators());
        Arrays.toString(students);
        System.out.println("Data without duplication:");
        for (int i = 0; i < k; i++) {
            System.out.println(students[i]);
        }
        if (listData.toArray().length == 0) {
            System.out.println("No duplicated Data");

        } else {
            System.out.println("Data with duplication:");
            System.out.println("ID/ LastName/Name/ Score");
            System.out.println(Arrays.toString(listData.toArray()));
        }

我尝试了nullhandlingExpecting方法,但我无法获得我想要的结果。

有没有办法避免在中断时将 null 值添加到数组中,或者在比较之前从数组中删除 null?

java 数组 循环 nullpointerexception null

评论

0赞 HariHaravelan 11/29/2022
如果要在 ID 或分数为 -1 时中断,请使用 while 循环并在其中添加这些条件,而不是中断
0赞 yasakrami 11/29/2022
非常感谢。您是否有可能将其编写为代码并确切地告诉将循环放在哪里,因为当我尝试这样做时,我仍然得到相同的结果。

答:

0赞 CODERZ 11/30/2022 #1

你可以把它放在一个while循环中,把你所有的代码都放进去,如果值是-1,就把中断它的条件放进去

0赞 AterLux 11/30/2022 #2

请注意,您的数组具有预定义的大小:k

Student[] students = new Student[k];

因此,如果用户需要在输入所有值之前中断输入,则必须截断数组。例如:k

            if (score == -1) {
                students = Arrays.copyOf(students, i);
                break;
            }

但最好考虑使用 ArrayList 而不是普通数组