Skip to content

Commit ed6400a

Browse files
authored
read user input (eugenp#11946)
* read user input * rename the unittest class
1 parent 32f98e9 commit ed6400a

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)