简体   繁体   中英

In Java how do I initialize elements in array in several lines, not one?

Hello this is a very simple question but I don't know the answer. I just want to know how to initialize every element of an array in several lines, because I know how to do it in one line.

My code of initializing them on one line is this way:

String input = scanner.nextLine();

String[] array = input.split("\\s+");

Using an ArrayList

String s = "Too Many\nLines Here\nNo its only three"; 
Scanner scanner = new Scanner(s); 
List<String> array = new ArrayList<>(Arrays.asList(scanner.nextLine().split("\\s+")));
//to add next line
array.addAll(Arrays.asList(scanner.nextLine().split("\\s+")));
//.. and so on   

In Java, Array must have fixed size, and you cannot change it once declared. About your problem, you can create an Array which has the size is greater than your expectation. Because you don't know how many it will loop, you can make the while loop and a marker to stop inputing ("quit" or "stop" or something else special user can't input...). Eg:

String[] arr = new String[1000];
Scanner scanner = new Scanner(System.in);
int counter = 0;

while (true) {
    String input = scanner.nextLine();
    if ("stop".equalsIgnoreCase(input)) {
        break;
    }
    arr[counter++] = input;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM