0

I am trying to write a program that takes input from a user, such as "1 5 3 6 3 5 0" all in one line. I would like to take this input and store each number in an array. So for example, my array would have values 1, 5, 3, 6, 3, 5, 0.

I do not even know where to start with this. I know to create a scanner. I thought that maybe I could do nextLine(); and then just separate it by spaces and put the values into an array.. However, nextLine() only takes strings.

3
  • 2
    And strings can be split(), if need be. Or you can take a number at a time. Try putting up what code you already have. Commented Apr 11, 2014 at 23:50
  • Integer.parseInt(String) Commented Apr 11, 2014 at 23:50
  • Whatever is put as command line argument is a String though it looks as a number. Commented Apr 11, 2014 at 23:51

4 Answers 4

2

You can use .split() or .chatAt(position) separate each element from the entire String.

String a = example.charAt(0); 

this would copy the first character, for example.

Sign up to request clarification or add additional context in comments.

Comments

1

Here you go, as long as the numbers are entered with spaces between them, this will populate an array of ints:

    System.out.println("Enter something > ");
    Scanner input = new Scanner(System.in);

    //read in string entered by user
    String inputString = input.nextLine();

    //split the string into an array of strings, using [space]
    String[] split = inputString.split(" ");

    //create a new int array, and populate it with the contents of the split string
    int intarray[] = new int[split.length];

    for (int i = 0; i < split.length; i++) {
        intarray[i] = Integer.parseInt(split[i]);
    }

Comments

0
String input = "1 5 3 6 3 5 0";
String[] inputs = input.split(" ");
ArrayList<Integer> values = new ArrayList<Integer>();
for (String s : inputs) {
     values.add(Integer.parseInt(s));
}
System.out.println(values);

This prints [1, 5, 3, 6, 3, 5, 0].

Comments

0

u may try nextInt():

Scanner scn = new Scanner(System.in);
int[] nums = new int[5];
out.printf("Enter %d numbers, space separated: ", nums.length);
for(int i = 0; nums.length > i; i ++) {
    nums[i] = scn.nextInt();
}
out.println("\nYour values are:");
for(int i : nums) {
    out.printf("%-8d", i);// u may use //out.printf("%d\t", i);
}

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.