File tree Expand file tree Collapse file tree
core-java-modules/core-java-io-4/src
main/java/com/baeldung/userinput
test/java/com/baeldung/userinput Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .userinput ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+ import java .util .Scanner ;
6+
7+ public class UserInputHandler {
8+
9+ public static List <String > readUserInput () {
10+ List <String > userData = new ArrayList <>();
11+ System .out .println ("Please enter your data below: (send 'bye' to exit) " );
12+ Scanner input = new Scanner (System .in );
13+ while (true ) {
14+ String line = input .nextLine ();
15+ if ("bye" .equalsIgnoreCase (line )) {
16+ break ;
17+ }
18+ userData .add (line );
19+ }
20+ return userData ;
21+ }
22+
23+ public static void main (String [] args ) {
24+ List <String > userData = readUserInput ();
25+ System .out .printf ("User Input Data:\n %s" , String .join ("\n " , userData ));
26+ }
27+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .userinput ;
2+
3+
4+ import org .junit .Test ;
5+
6+ import java .io .ByteArrayInputStream ;
7+ import java .io .InputStream ;
8+ import java .util .Arrays ;
9+ import java .util .List ;
10+ import java .util .stream .Collectors ;
11+
12+ import static org .assertj .core .api .Assertions .assertThat ;
13+
14+ public class UserInputHandlerUnitTest {
15+
16+ @ Test
17+ public void givenDataInSystemIn_whenCallingReadUserInputMethod_thenHaveUserInputData () {
18+ String [] inputLines = new String []{
19+ "The first line." ,
20+ "The second line." ,
21+ "The last line." ,
22+ "bye" ,
23+ "anything after 'bye' will be ignored"
24+ };
25+ String [] expectedLines = Arrays .copyOf (inputLines , inputLines .length - 2 );
26+ List <String > expected = Arrays .stream (expectedLines ).collect (Collectors .toList ());
27+ InputStream stdin = System .in ;
28+ try {
29+ System .setIn (new ByteArrayInputStream (String .join ("\n " , inputLines ).getBytes ()));
30+ List <String > actual = UserInputHandler .readUserInput ();
31+ assertThat (actual ).isEqualTo (expected );
32+ } finally {
33+ System .setIn (stdin );
34+ }
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments