Created
September 4, 2015 09:50
-
-
Save V0L0DYMYR/c9ad75a877a2d8256431 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.*; | |
| import java.util.Iterator; | |
| public class StringTokenizer implements Iterable<String>, Iterator<String> { | |
| private InputStream in; | |
| public StringTokenizer(InputStream in) { | |
| this.in = in; | |
| } | |
| public String nextToken() throws IOException { | |
| StringBuilder buf = new StringBuilder(); | |
| int c; | |
| while ((c = in.read()) != -1) { | |
| buf.append((char)c); | |
| } | |
| return buf.toString(); | |
| } | |
| @Override | |
| public Iterator<String> iterator() { | |
| return this; | |
| } | |
| @Override | |
| public boolean hasNext() { | |
| try { | |
| return in.available() != 0; | |
| } catch (IOException e) { | |
| throw new RuntimeException(e); | |
| } | |
| } | |
| @Override | |
| public String next() { | |
| char c = 0; | |
| try { | |
| while (in.available() != 0) { | |
| c = (char)in.read(); | |
| if (Character.isLetter(c)) { | |
| return String.valueOf(c); | |
| } | |
| } | |
| } catch (IOException e) { | |
| throw new RuntimeException(e); | |
| } | |
| return ""; | |
| } | |
| @Override | |
| public void remove() { | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.junit.Test; | |
| import org.mockito.Mockito; | |
| import java.io.IOException; | |
| import java.io.InputStream; | |
| import java.util.ArrayList; | |
| import java.util.Iterator; | |
| import java.util.List; | |
| import static org.junit.Assert.assertEquals; | |
| import static org.mockito.Mockito.when; | |
| public class StringTokenizerTest { | |
| @Test | |
| public void test() throws IOException { | |
| InputStream in = Mockito.mock(InputStream.class); | |
| StringTokenizer reader = new StringTokenizer(in); | |
| when(in.read()).thenReturn((int) 'a', (int) ' ', (int) 'b' - 1); | |
| when(in.available()).thenReturn(3, 2, 1, 0); | |
| List<String> actual = new ArrayList<String>(); | |
| Iterator<String> iterator = reader.iterator(); | |
| while (iterator.hasNext()) { | |
| String word = iterator.next(); | |
| actual.add(word); | |
| } | |
| List<String> expected = new ArrayList<String>(); | |
| expected.add("a"); | |
| expected.add("b"); | |
| assertEquals(2, actual.size()); | |
| assertEquals(expected, actual); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment