Prabhjot Rai
Prabhjot Rai

Reputation: 27

Taking integers as input from console and storing them in an array

When I am trying to write the following code, the computer takes several inputs. But what I want is it should take only one line as an input and save all the integers in that line in an array. Can you help me with this please?

import java.util.*;

class InputInteger{

    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        int[] array=new int[20];
        int i=0;
        while(input.hasNext()){
          array[i]=input.nextInt();
          i++;
        }     
        input.close();
    }       
}

Upvotes: 1

Views: 3891

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201439

But what I want is it should take only one line as an input and save all the integers in that line in an array.

First, I urge you not to close() a Scanner that you have created around System.in. That's a global, and close()ing can cause you all kinds of issues later (because you can't reopen it). As for reading a single line of input and splitting int values into an array, you could do use Scanner.nextLine() and something like

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    if (input.hasNextLine()) {
        String line = input.nextLine();
        String[] arr = line.split("\\s+");
        int[] vals = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            vals[i] = Integer.parseInt(arr[i]);
        }
        System.out.println(Arrays.toString(vals));
    }
}

Edit Based on your comment,

String line = "1 31 41 51";
String[] arr = line.split("\\s+");
int[] vals = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
    vals[i] = Integer.parseInt(arr[i]);
}
System.out.println(Arrays.toString(vals));

Output is

[1, 31, 41, 51]

If you need to handle errors, I suggest you use a List like

List<Integer> al = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
    try {
        al.add(Integer.parseInt(arr[i]));
    } catch (NumberFormatException nfe) {
    }
}
// You could now print the List
System.out.println(al);
// And if you must have an `int[]` copy it like.
int[] vals = new int[al.size()];
for (int i = 0; i < al.size(); i++) {
    vals[i] = al.get(i);
}
System.out.println(Arrays.toString(vals));

Upvotes: 2

DnR
DnR

Reputation: 3507

You can capture the input as String and use for loop to process it:

Scanner input=new Scanner(System.in);
int[] array=new int[20];
String numbers = input.nextLine();
for(int i = 0 ; i<numbers.length() ; i++){
    array[i]=Character.getNumericValue(numbers.charAt(i));
}  

But in this case, the number of digits must be not exceed your array size, which is 20. Or else it will throw ArrayIndexOutOfBound Exception. You may want to do Exception handling on this.

Or to avoid that, you can declare your array with size equal to length of the input:

int[] array=new int[numbers.length()];

See the demo here

Upvotes: 1

David.Jones
David.Jones

Reputation: 1411

    Scanner input = new Scanner(System.in);
    ArrayList<Integer> nums = new ArrayList<Integer>();

    boolean repeat = true;
    while (repeat) {
        System.out
                .print("Enter a bunch of integers seperated by spaces, or 'q' to quit: ");
        String line = input.nextLine();
        if (line.equals("q"))
            repeat = false;
        else {
            String[] numbers = line.split("\\s+");
            for (String num : numbers) {
                if (!nums.contains(num))
                    nums.add(Integer.parseInt(num));
            }
        }
    }
    for (Integer i : nums) {
        System.out.println(i);
    }
    input.close();

Upvotes: 0

Related Questions