简体   繁体   English

ArrayList 不会添加我的随机数元素 [JAVA]

[英]ArrayList will not add my elements of random numbers [JAVA]

this is my first question and if you knew me you'd know id have to be completely lost to be asking a question on here.这是我的第一个问题,如果你认识我,你就会知道 id 必须完全迷失才能在这里提问。

My arraylist is continuously empty and refuses to add elements no matter what I do, I am just trying to fill it with random numbers between 1 and 50, then print those numbers as a string.我的数组列表一直为空,无论我做什么都拒绝添加元素,我只是想用 1 到 50 之间的随机数填充它,然后将这些数字打印为字符串。 I've been trying to find a solution for 4-5 hours with no luck.我一直在努力寻找解决方案 4-5 个小时,但没有运气。 I'm not receiving an error when I run my code, but the arraylist is always empty and won't add any elements.我在运行代码时没有收到错误消息,但 arraylist 始终为空并且不会添加任何元素。 If anyone can see what I'm doing wrong I would be very grateful, thank you in advance.如果有人能看到我做错了什么,我将不胜感激,在此先感谢您。

This is my numbers class:这是我的数字课:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class Numbers {

private int size = 0;

ArrayList<Integer> array = new ArrayList<Integer>(size);

public Numbers() {

}

public Numbers(int n) {
    size = n;
}

public void generateNumbers() {
    Random random = new Random();
    for (int i = 0; i < size; i++) {

        array.add(random.nextInt(49) + 1);
    }

}

public void findCount(int find) {
    int count = Collections.frequency(array, find);
    System.out.println("Number " + find + " occurred " + count + " times in the array");
}

@Override
public String toString() {
    return array.toString();
}

public void isArrayCreated() {
    if (size == 00) {
        System.err.print("Array is not created... please create the array first");
        System.out.println();
    }
}

public void isEmpty() {
    if (array.isEmpty()) {

        System.err.print("Array is empty");
        System.out.println();
        System.out.println(size);

    }
}

}

and this is my test class:这是我的测试课:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Lab2Test {

public static void main(String[] args) {
    int n = 0;
    boolean loop = true;
    Scanner input = new Scanner(System.in);

    while (loop == true) {
        int option = 0;
        System.out.println("1. Create array with new size");
        System.out.println("2. Generate random numbers and store it in the array");
        System.out.println("3. Search a number and display its number of occurrences");
        System.out.println("4. Display array");
        System.out.println("5. Quit");
        System.out.println("Enter your option: ");

        try {
            option = input.nextInt();
        } catch (InputMismatchException e) {
            System.out.print("******Input mismatch exception*****");
            System.out.println();
            System.out.println();
        }

        if (option == 1) {
            try {
                System.out.println("Enter required size: ");
                n = input.nextInt();
            } catch (InputMismatchException a) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

        }
        Numbers numb = new Numbers(n);

        if (option == 2) {
            numb.generateNumbers();

        }

        if (option == 3) {
            int find = 0;
            System.out.println("Enter the number to be searched: ");
            try {
                find = input.nextInt();
            } catch (InputMismatchException e) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

            numb.findCount(find);

        }

        if (option == 4) {
            // numb.isArrayCreated();
            numb.isEmpty();
            numb.toString();

        }

        if (option == 5) {
            System.out.println("Bye.... have a nice day!");
            loop = false;

        }

    }

}

}

The problem is that Numbers object is declared and instantiated inside the while loop.问题是 Numbers 对象是在 while 循环中声明和实例化的。 So in each iteration your Numbers is destroyed and created again.因此,在每次迭代中,您的 Numbers 都会被销毁并再次创建。 To solve it you should move Numbers outside the loop.要解决它,您应该将 Numbers 移到循环之外。

Try this尝试这个

import java.util.InputMismatchException;
import java.util.Scanner;

public class Lab2Test {

public static void main(String[] args) {
    int n = 0;
    boolean loop = true;
    Scanner input = new Scanner(System.in);
    Numbers numb; // Here we have a reference to Numbers outside the loop, so it's not destroyed and recreated in each iteration.

    while (loop == true) {
        int option = 0;
        System.out.println("1. Create array with new size");
        System.out.println("2. Generate random numbers and store it in the array");
        System.out.println("3. Search a number and display its number of occurrences");
        System.out.println("4. Display array");
        System.out.println("5. Quit");
        System.out.println("Enter your option: ");

        try {
            option = input.nextInt();
        } catch (InputMismatchException e) {
            System.out.print("******Input mismatch exception*****");
            System.out.println();
            System.out.println();
        }

        if (option == 1) {
            try {
                System.out.println("Enter required size: ");
                n = input.nextInt();
                numb = new Numbers(n); // Here we create a new sized Numbers

            } catch (InputMismatchException a) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

        }

        if (option == 2) {
            numb.generateNumbers();

        }

        if (option == 3) {
            int find = 0;
            System.out.println("Enter the number to be searched: ");
            try {
                find = input.nextInt();
            } catch (InputMismatchException e) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

            numb.findCount(find);

        }

        if (option == 4) {
            // numb.isArrayCreated();
            numb.isEmpty();
            numb.toString();

        }

        if (option == 5) {
            System.out.println("Bye.... have a nice day!");
            loop = false;

        }

    }

}

}

PD: After these changes you could get NullpointerExceptions when you use other options before 1, so you need to fix it. PD:在这些更改之后,当您使用 1 之前的其他选项时,您可能会得到 NullpointerExceptions,因此您需要修复它。 Just provided a solution to your problem, but it needs more work.刚刚为您的问题提供了解决方案,但还需要做更多的工作。

As @Ezequiel said the problem is that every time you are creating a new object and assign it to numb .正如@Ezequiel 所说,问题在于每次您创建一个新对象并将其分配给numb

I hope this can help you, now it also display the value of the array我希望这可以帮助你,现在它也显示数组的值

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.InputMismatchException;
import java.util.Scanner;

class Numbers {

private int size;

ArrayList<Integer> array ;

public Numbers() {

}

public Numbers(int n) {
    size = n;
    array = new ArrayList<Integer>(size);
}

public void generateNumbers() {
    Random random = new Random();
    for (int i = 0; i < size; i++) {
        array.add(random.nextInt(49) + 1);
    }

}

public void findCount(int find) {
    int count = Collections.frequency(array, find);
    System.out.println("Number " + find + " occurred " + count + " times in the array");
}

@Override
public String toString() {
 return array.toString();
}

public void isArrayCreated() {
    if (size == 00) {
        System.err.print("Array is not created... please create the array first");
        System.out.println();
    }
}

public void isEmpty() {
    if (array.isEmpty()) {

        System.err.print("Array is empty");
        System.out.println();
        System.out.println(size);

    }
}

}




public class Main {

public static void main(String[] args) {
    int n = 0;
    boolean loop = true;
    Scanner input = new Scanner(System.in);
Numbers numb = new Numbers(n);
    while (loop == true) {
        int option = 0;
        System.out.println("1. Create array with new size");
        System.out.println("2. Generate random numbers and store it in the array");
        System.out.println("3. Search a number and display its number of occurrences");
        System.out.println("4. Display array");
        System.out.println("5. Quit");
        System.out.println("Enter your option: ");

        try {
            option = input.nextInt();
        } catch (InputMismatchException e) {
            System.out.print("******Input mismatch exception*****");
            System.out.println();
            System.out.println();
        }

        if (option == 1) {
            try {
                System.out.println("Enter required size: ");
                n = input.nextInt();
                numb = new Numbers(n);
            } catch (InputMismatchException a) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

        }
        

        if (option == 2) {
            numb.generateNumbers();

        }

        if (option == 3) {
            int find = 0;
            System.out.println("Enter the number to be searched: ");
            try {
                find = input.nextInt();
            } catch (InputMismatchException e) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

            numb.findCount(find);
            numb.toString();

        }

        if (option == 4) {
            // numb.isArrayCreated();
            numb.isEmpty();
           System.out.println( numb.toString());

        }

        if (option == 5) {
            System.out.println("Bye.... have a nice day!");
            loop = false;

        }

    }

}

}

The problem lies with your Test class, in the line Numbers numb = new Numbers(n);问题在于您的Test类,在Numbers numb = new Numbers(n); . . Everytime your loop is run, the value of numb from the previous iteration gets destroyed and a new object numb is created again.每次运行循环时,前一次迭代中的numb值都会被销毁,并再次创建一个新对象numb You should rather declare your numb variable outside the loop as您应该在循环外将numb变量声明为

import java.util.InputMismatchException;
import java.util.Scanner;

public class Lab2Test {

public static void main(String[] args) {
    int n = 0;
    boolean loop = true;
    Numbers numb = new Numbers(0);
    Scanner input = new Scanner(System.in);

    while (loop == true){
        int option = 0;
        System.out.println("1. Create array with new size");
        System.out.println("2. Generate random numbers and store it in the array");
        System.out.println("3. Search a number and display its number of occurrences");
        System.out.println("4. Display array");
        System.out.println("5. Quit");
        System.out.println("Enter your option: ");

        try {
            option = input.nextInt();
        } catch (InputMismatchException e) {
            System.out.print("******Input mismatch exception*****");
            System.out.println();
            System.out.println();
        }

        if (option == 1) {
            try {
                System.out.println("Enter required size: ");
                n = input.nextInt();
            } catch (InputMismatchException a) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

        }
        Numbers numb = new Numbers(n);

        if (option == 2) {
            numb.generateNumbers();

        }

        if (option == 3) {
            int find = 0;
            System.out.println("Enter the number to be searched: ");
            try {
                find = input.nextInt();
            } catch (InputMismatchException e) {
                System.out.print("******Input mismatch exception*****");
                System.out.println();
                System.out.println();
            }

            numb.findCount(find);

        }

        if (option == 4) {
            // numb.isArrayCreated();
            numb.isEmpty();
            numb.toString();

        }

        if (option == 5) {
            System.out.println("Bye.... have a nice day!");
            loop = false;

        }

    }

}

}

Generally too, it is considered to be a nice practice to declare all your variables outside the loop.一般来说,在循环外声明所有变量也被认为是一种很好的做法。 This also reduces your space complexity, and removes the possibility of such errors as encountered by you.这也降低了您的空间复杂度,并消除了您遇到此类错误的可能性。

Also, in your functions, you can add a condition to check if (size == 0) .此外,在您的函数中,您可以添加一个条件来检查if (size == 0) If it is the case, a proper message should be displayed and an appropriate return code returned.如果是这种情况,则应显示正确的消息并返回适当的返回代码。 This way no NullPointerException will be generated.这样就不会产生NullPointerException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM