0
votes

I'm trying to read in a list of Integers from a scanner, using user input, and store all input into an ArrayList, except the last integer the user inputs, of which I want to store within an Integer, (Integer key;) How can I do this?

I've tried putting it into a int[] first but I don't know how many integers the user will input. Is there a way to directly read in all integers to the ArrayList excluding the last one, which would be stored within the Integer key?

What I have so far:

private ArrayList<Integer> theList;
private Integer theKey;
public static void main(String args[])
{
    int[] integers = null;
    System.out.println("Enter a list of integers, the final being a key");
    Scanner scanner = new Scanner(System.in);
    int i = 0;
    try
    {
       while (scanner.hasNext())
       {
         integers[i] = scanner.nextInt();
         i++;
       }
    }
    catch (NullPointerException ex)
    {
    }
    for (int k = 0; i < integers.length; i++)
    {
        System.out.print(integers[k] + " ");
    }


}
2
Post your code here. That is, in your question. And not on external pages. - Sufian
To add to @Sufian's comment, welcome to Stack Overflow. To indent your code when you edit, paste it into the html text box, highlight it and press ctrl-k. - Elliott Frisch
Ahh, thank you. So I guess you can just copy paste code into the text field and it can tell that it's code and not just regular writing? - LogwanaMan
@LogwanaMan No, the ctrl-k will indent it to the proper level (4 spaces) to be seen as code. - Elliott Frisch

2 Answers

3
votes

You could use a List<Integer>. Read all of the ints into it, and then (when there are no more ints), remove the last one. Something like,

System.out.println("Enter a list of integers, the final being a key");
Scanner scanner = new Scanner(System.in);
List<Integer> al = new ArrayList<>();
while (scanner.hasNextInt()) {
    al.add(scanner.nextInt());
}
int key = al.remove(al.size() - 1); // <-- the last one is removed, and returned.
0
votes

You can save all numbers in list than assign last element to some variable and than remove the last element from the list.