input string a list in java

htt‮p‬s://www.lautturi.com
input string a list in java

To input a list of strings in Java, you can use the Scanner class or the BufferedReader class.

Here is an example of how to use the Scanner class to input a list of strings:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<String> list = new ArrayList<>();
        System.out.println("Enter a list of strings, one per line. Enter 'q' to quit.");
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            if (line.equals("q")) {
                break;
            }
            list.add(line);
        }
        System.out.println("Your list: " + list);
        sc.close();
    }
}

In this example, the Scanner class is used to read input from the console. The hasNextLine() method is used to check if there is a line of input available, and the nextLine() method is used to read the line as a String. The String is added to the list if it is not equal to "q", and the loop continues until the end of input is reached.

Here is an example of how to use the BufferedReader class to input a list of strings:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        ArrayList<String> list = new ArrayList<>();
        System.out.println("Enter a list of strings, one per line. Enter 'q' to quit.");
        String line = br.readLine();
        while (!line.equals("q")) {
            list.add(line);
            line = br.readLine();
        }
        System.out.println("Your list: " + list);
        br.close();
    }
}

In this example, the BufferedReader class is used to read input from the console. The readLine() method is used to read a line of input as a String, and the String is added to the list if it is not equal to "q". The loop continues until the end of input is reached.

For more information on the Scanner class and the BufferedReader class in Java, you can refer to the Java documentation and the Java tutorial.

Created Time:2017-11-01 22:29:52  Author:lautturi