Created
June 22, 2011 11:29
-
-
Save guohai/1039911 to your computer and use it in GitHub Desktop.
An Example of Recursion, see http://en.wikipedia.org/wiki/Recursion
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.IOException; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| import java.util.Random; | |
| public class RecursionMethodDemo { | |
| public static void main(String[] args) { | |
| List<String> list = new ArrayList<String>(); | |
| list.add("hello"); | |
| list.add("world"); | |
| list.add("beautiful"); | |
| list.add("girl"); | |
| recursion(list, 0); | |
| } | |
| public static void recursion(List<String> list, int ix) { | |
| if (ix >= list.size()) { | |
| return; | |
| } | |
| try { | |
| doSomething(list.get(ix)); | |
| // just an example, so i take an exception to control the logic | |
| // flow, better not do this in critical condition | |
| } catch (IOException e) { | |
| System.err.println(ix + 1); | |
| recursion(list, ix + 1); | |
| } | |
| } | |
| public static void doSomething(String msg) throws IOException { | |
| int seed = (int) Math.floor(new Random().nextFloat() * 10 + 1); | |
| if (seed == 4 || seed == 5 || seed == 8) { | |
| throw new IOException( | |
| "I'm not going to do that, you can change another one..."); | |
| } | |
| System.out.println(msg); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment