0

I have some problems with making an array. What I'm supposed to to is to make an array that contains 5 text-strings with names from the terminal. How do I do this? I know how to make an array with my own values, but this was harder to solve than I expected. And yes, I'm new to programming ;)

1
  • 2
    Probably args is what you are getting from command line. Commented Sep 9, 2016 at 11:35

2 Answers 2

1

A number of ways to do this:

String[] elements = new String[5];
for(int i = 0; i <= 4; i++){
     System.out.println("Please enter an element");
     elements[i]= input.next();

}

that's exactly doing what you are looking for.

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

Comments

0

I hope this program can help you.

import java.util.Scanner;

public abstract class Main {

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter number of elements");
        int num_of_elements = Integer.parseInt(input.next());
        String[] elements =new String[num_of_elements];
        for(int i = 0; i < num_of_elements; i++){
            System.out.println("Please enter an element");
            elements[i]= input.next() + " ";
        }
        for(int i = 0; i < num_of_elements; i++){
            System.out.println("[" + elements[i] + "]");
        }
    }
}

Test

Please enter number of elements
3
Please enter an element
H
Please enter an element
E
Please enter an element
Y
[H ]
[E ]
[Y ]

Test 2

Please enter number of elements
4
Please enter an element
Hello
Please enter an element
How
Please enter an element
are
Please enter an element
you?
[Hello ]
[How ]
[are ]
[you? ]

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.