I need to solve an exercise that work like the following:
- A user start adding integers into an array;
- When he want to stop adding numbers, he should type
-1; - After typing
-1, a message appears where it display the numbers added, with thecountof 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.
ArrayList, which will automatically take care of all that for you.-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 :Dsplit(" ")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 usingInteger.parseInt(stringArray[indexOfLoop]);