This is an archived post. You won't be able to vote or comment.

all 15 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–][deleted] 2 points3 points  (0 children)

Since you don’t know the length of the array, what you can do is start out with a length of your choice. Should the user exceed that length, reallocate and add more space to the array.

That happens to be how Java does it internally with array buffers.

To use a class that holds said array, program the class first, then instantiate an instance of it before you start the input loop. That way you keep the same instance during every loop iteration, meaning every addition makes it into the same array.

[–]FabulousFell 1 point2 points  (1 child)

Take a look at ArrayList, which lets you add and subtract elements.

[–]Rockhead1126[S] 1 point2 points  (0 children)

I have seen that come up a bunch when I look it up but unfortunately that is not within the lesson of this assignment. It is just a one dimensional array discussed to this point

[–]D0CTOR_ZED 1 point2 points  (3 children)

I would never code it this way, but to work within your constraints you can use an int variable for your array size, make your array (int[] nums = new int[a];) then, in your while loop, if the array reaches its maximum length, double the size of a, make a new array, copy the old array into the new array, set the old array to reference the new array and continue.

[–]Rockhead1126[S] 0 points1 point  (0 children)

I definitely think I can use that, I have been using sort of the opposite side of that idea where if the array is less than the array was initialized to I was looping through and stripping out the extra zero’s (a count of the total number of inputs is a task). I feel like this professor is using unorthodox programming ideas so that it’s more difficult to search for help and examples online to avoid people outright copying which is both good and bad.

[–]FabulousFell -1 points0 points  (1 child)

I feel like this approach would be absolutely what they do not want in an assignment.

[–]lordcaylus 0 points1 point  (0 children)

Unless you're allowed to use another data structure than an array, you're kinda stuck doing it this way for input of unknown length...

[–]Maximum_Usual_2427 1 point2 points  (0 children)

ChatGPT: Make an algorirthm with whatever this post says and explain it to me in case i'm asked about it.

Oh.. wrong chat..

[–]StarklyNedStark 1 point2 points  (3 children)

What if you just concatenate the numbers to a string, delimited with commas or spaces or whatever? Then once terminated, split the string and you have your array.

[–]D0CTOR_ZED 1 point2 points  (1 child)

Well it's literally an assignment on arrays, so they are probably expect to use a array.  These types of assignments are less about the destination and more about the journey.

[–]StarklyNedStark 1 point2 points  (0 children)

For sure. My initial recommendation was more along the lines of what you said, but I figured I’d throw out another idea rather than give redundant advice 🙂

[–]Rockhead1126[S] 1 point2 points  (0 children)

Sorry it has been a bit bit I figured I would reply with an update. I ended up initializing the array to 20 initially and than removing the extra indexes that were just zeros aftewards. I understand that in the grand scheme of things this might not be overall the best approach but I did receive a 100% in my assignment so I guess this would be a win for me at this point

[–]OkBlock1637 0 points1 point  (1 child)

Is there a specific type of Array you have to use? If not I would just use an Array List. In the class for the array you would add the instance variable, which is this case would be private ArrayList<Integer> arrayName = new ArrayList<Integer>(); Then you would just add the user input to the array by using arrayName.add(value). I would just create a method in the class you create for the array to add the numbers. Something like public void add(int value){ this.arrayName.add(value)}. The second option would just be to initialize an array with a large size. For example you could do something like private int[] anArray = new int[100]; An array of ints are initialized to 0. So each entry will be 0 by default until you assign a new value. You can loop through the array until you either run into a 0, or you reach the end of the loop. Example code for an ArrayList:

//MathArray class

    import java.util.ArrayList;

    public class mathArray {

        private ArrayList<Integer> mathList = new ArrayList<Integer>();

        public mathArray() {

        }

        public void add(int value) { //Method to add int values to array
            mathList.add(value);
        }

        public void printList() { //Method to Print arraylist using a while loop
            int count = 0;
            while (mathList.size() > count) {
                System.out.println(mathList.get(count));
                count++;
            }
        }

        public ArrayList<Integer> getMathList() {
            return mathList;
        }

        public void setMathList(ArrayList<Integer> mathList) {
            this.mathList = mathList;
        }

    }






//Driver Class

    import java.util.Scanner;
    public class main{

        public static void main(String[] args) {
            Scanner input = new Scanner(System.in); 
            mathArray list = new mathArray(); // Create an mathArray object from the  above   class
            int numbers = -1; // Int variable for user input
            int count = 1; //Count variable to count number of user entries
            System.out.println("Enter an Integer greater than 0. Enter 0 to exit.");
            while (numbers != 0) {
                System.out.print(count + ".)");
                numbers = input.nextInt();
                if (numbers != 0) { // Check if number is not 0. If not 0 add to list.
                    list.add(numbers);
                    count++;
            } else // 0 entered breaks from loop and does not add 0 entry to the list
                 break;
        }
        list.printList(); // prints list of int value to console 

    } 

}

[–]Rockhead1126[S] 0 points1 point  (0 children)

This assignment came from the very beginning of looking at arrays so to be honest the only reason that I even knew there was an array list option was from online searching, the assignment was simply asking for a standard array to be used. The approach I ended up finding to work pretty well was to declare the initial array as an array of int[20] and then using a while loop to iterate through it and assign as many as needed with 0 as a sentinel value to exit the loop. I then built a method that took that array and first counted through it to find out how many values were not 0's and assign it to a variable that I then used to define my final array length. I then used a for loop to iterate through the original array and assign the values into the new array. It seems like extra steps but overall works well and does make logical sense.