0

I need to solve an exercise that work like the following:

  1. A user start adding integers into an array;
  2. When he want to stop adding numbers, he should type -1;
  3. After typing -1, a message appears where it display the numbers added, with the count of them

So if he entered: 1 8 6 9 -1

The result would be:

Numbers entered are: 1 8 6 9 -1 And the count is 5.

I tried to write the code:

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class exercice
{
    public static void main (String[] args) throws java.lang.Exception
    {
        readNumbers();
    }
//No parameters inside: just readNubers()
    public static void readNumbers()
    {
        int[] num = new int[n];
        int x = 0;
        while(x!=-1)
        {
            for(int i=0; i<n; i++)
            {
                System.out.println("Enter a number");
                Scanner scan = new Scanner(System.out);
                x = scan.nextInt();
                num[i]=x;
            }
        }
        for(int j = 0; j<num.length; i++)
        {
            System.out.println(num[i]);
            System.out.println("The total of entered numbers is: "+num.length);
        }
    }
}

But, I am still stuck at how to define a variable array length, without using ArrayList. SO I need to solve it like this code above.

In out course, we have an example where we can define an array with unknown length like this:

method_name(int ...a) but can't know how to use it.

4
  • You can't define a variable length array. You'll have to guess at the size, and then make a resized array (and copy over) as needed. The correct approach is to just use ArrayList, which will automatically take care of all that for you. Commented Feb 1, 2016 at 20:14
  • I had an idea of a recursive method that calls itself if the user doesn't enter -1, passing the current size. When the user does enter -1, it creates the array, and fills it from the end, returning the current state, and each previous call putting their value in the appropriate place. But it's a horrible solution :D Commented Feb 1, 2016 at 20:17
  • There is a much simpler solution than what everyone is posting that I'm working on. It'll be a few minutes, though Commented Feb 1, 2016 at 20:18
  • Are you allowed to use Strings? You could capture the numbers in a string, with spaces in between, then split(" ") it on the space to get a string array. Make an integer array with the same length, and convert all the methods into the other using Integer.parseInt(stringArray[indexOfLoop]); Commented Feb 1, 2016 at 20:33

3 Answers 3

2

In out course, we have an example where we can define an array with unknown length like this:

method_name(int ...a) but can't know how to use it.

That isn't applicable here: even in that case, the actual array size must be known at compile time. When you call a varargs method, you always know the actual size of the array (or you're passing in an array object which was sized somewhere else).

If you can't use ArrayList, you have to reinvent it: you will have to manually create a bigger array and then copy the contents of the small array into your bigger array. This is what ArrayList does internally. (Alternately, you could start with a huge array, fill only part of it, and then pick out the part you need.)

All Java arrays have their size fixed at their time of creation.

Sign up to request clarification or add additional context in comments.

Comments

0

If you can't use a list, your options are:

  1. Define a really big array and fill as much of it as you need

or

  1. When your array gets full, make a new one and copy the content across.

Or, of course, you could construct the string listing the numbers as you go, and not store them in an array at all.

Comments

0

I didn't read the part that said "I need to solve an exercise" and apologize for giving the full solution. I am adding some hints at the beginning, and a spoiler alert at the end.

You can store the numbers in a String variable, separated by a space. Then, you can split that into a String array. Finally, set an int array size to match the String array and parse the data into it.

Full Solution:

Here is the code to store the numbers into an int array:

Scanner input = new Scanner(System.in);

System.out.print("Please enter the numbers: ");
int nextNum = 0;
String nums = "";
do{
    nextNum = input.nextInt();
    nums += nextNum + " ";
}while(nextNum != -1);

String[] nums2 = nums.split(" ");
int[] x = new int[nums2.length];

for(int i = 0; i < nums2.length; i++)
    x[i] = Integer.parseInt(nums2[i]);

You now have an array (x) with all the numbers the user entered. What happens is the numbers are added to a String, and separated by a space. Then, after the user enters -1, the String is converted into a String array. Finally, it parses the int from each element of the String array, and puts it in its own int array element.

Hope this helps!

2 Comments

This really amounts to obfuscation of the issue. The compiler creates a temporary StringBuilder to do each string concatenation, which means constantly copying strings back and forth. That, and parsing the integers, converting them to strings, and parsing them again, will make this perform much worse than an ArrayList or indeed, creating new arrays and copying the data each time. Remember, a String is really just a specialized array. Still, it's an interesting way to solve the problem.
The OP states that ArrayLists cannot be used. I gave the best answer I could think of, while showing a way to workaround the fact that an array has to be a set size. @JohnSensebe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.