1

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();
    }       
}

3 Answers 3

2

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but this prints an error when I input numbers like 1 31 41 51 etc. How can that be dealt with?
Edited based on your comment. What is etc?
1

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

2 Comments

Thanks. But what if my input is like this: 1 21 31 41 51 and so on. In this case how will I make an array of integers 1, 21, 31, 41 etc?
@PrabhjotRai ah good question! For that case, you should refer to @Elliott Frisch answer
0
    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();

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.