read user input (#11946)

* read user input

* rename the unittest class
This commit is contained in:
Kai Yuan 2022-03-27 18:24:31 +02:00 committed by GitHub
parent c9637e95fd
commit 3eeb5c7d2b
2 changed files with 63 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package com.baeldung.userinput;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class UserInputHandler {
public static List<String> readUserInput() {
List<String> userData = new ArrayList<>();
System.out.println("Please enter your data below: (send 'bye' to exit) ");
Scanner input = new Scanner(System.in);
while (true) {
String line = input.nextLine();
if ("bye".equalsIgnoreCase(line)) {
break;
}
userData.add(line);
}
return userData;
}
public static void main(String[] args) {
List<String> userData = readUserInput();
System.out.printf("User Input Data:\n%s", String.join("\n", userData));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.userinput;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class UserInputHandlerUnitTest {
@Test
public void givenDataInSystemIn_whenCallingReadUserInputMethod_thenHaveUserInputData() {
String[] inputLines = new String[]{
"The first line.",
"The second line.",
"The last line.",
"bye",
"anything after 'bye' will be ignored"
};
String[] expectedLines = Arrays.copyOf(inputLines, inputLines.length - 2);
List<String> expected = Arrays.stream(expectedLines).collect(Collectors.toList());
InputStream stdin = System.in;
try {
System.setIn(new ByteArrayInputStream(String.join("\n", inputLines).getBytes()));
List<String> actual = UserInputHandler.readUserInput();
assertThat(actual).isEqualTo(expected);
} finally {
System.setIn(stdin);
}
}
}