idontunderstandarrays
idontunderstandarrays

Reputation: 351

Extract each seperate number from string

I have this as an input "1 2 3 4 5" and I want to have it like this

int[] numbers = new int[5];
number[0] = 1;
number[1] = 2;
number[2] = 3;
number[3] = 4;
number[4] = 5;

So how can I extract each number from a string and put it in an int array?

    ConsoleIO io = new ConsoleIO();
    int[] numbers = new int[5];

    io.writeOutput("Type in 5 numbers");

    String input = io.readInput();

    // If input is longer than 1 character for example, "1 2 3 4 5"
    if(input.length() > 1) {
        System.out.println(input.length());
        for(int y = 0; y < io.readInput().length(); y++) {
            numbers[y] = Integer.parseInt(io.readInput().substring(y, io.readInput().indexOf(" "))); 
        }
        return;
    }
    // If input is one number for example, "1"
    else {
        for(int i = 0; i < numbers.length; i++) {
            numbers[i] = Integer.parseInt(io.readInput());
        }
    }

The else works, so if I enter one number and press enter and then the next one, it's all good. But if I have a sequence of numbers with a space in between ("1 2 3 4 5") the program just breaks.

Upvotes: 0

Views: 129

Answers (4)

Alexandru Ionescu
Alexandru Ionescu

Reputation: 1

import java.util.*;
public class Solution {
    public static void main(String []args) {
        Scanner in = new Scanner(System.in);
        String[] nums = in.nextLine().split(" ");
        int[] numbers = new int[5];
        for(int i = 0; i <5; i++) {
            numbers[i] = Integer.parseInt(nums[i]);
            System.out.println(numbers[i]);
        }
    }
}

Upvotes: 0

Joeri Akkerman
Joeri Akkerman

Reputation: 34

String input = io.readInput();
int[] arr = new int[5];

if(input.length() >= 5){
    String[] c = input.split(" ");
    for(int i = 0; i < c.length(); i++){
        arr[i] = Integer.parseInt(c[i]);
    }
}

Upvotes: 1

Owen Cao
Owen Cao

Reputation: 8183

Assume your input is always numbers with a space between each other (or just one number), in Java 8 you can work in this way:

String[] splits = input.split(" ");
int[] result =  Arrays.stream(splits).mapToInt(Integer::parseInt).toArray();

Upvotes: 1

GBlodgett
GBlodgett

Reputation: 12819

Why not use a Scanner and then split and parse?

Scanner in = new Scanner(System.in);
String[] nums = in.nextLine().split(" ");
for(int i = 0; i <=5; i++) {
   numbers[i] = Integer.parseInt(nums[i]);
}

Upvotes: 1

Related Questions