`
小明哥
  • 浏览: 86794 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

路径选择2

    博客分类:
  • Java
阅读更多

我们将上次的问题变化一下

 

要求在 输入一个整数n,然后使用递归算法在一个JTextArea中输出所有 1到n的路径。
例如n=4,则输出:

1-4
1-2-4

1-3-4
1-2-3-4


多了1-3-4  问题就变得复杂了 

最后运用正则表达式这个强大的工具解决

 

用循环:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class way {
	public static void main(String[] args) {
		int x = 1, y, z;
		String str = "";
		Scanner scan = new Scanner(System.in);
		y = scan.nextInt();
		while (x < y) {
			str += x + "-";
			System.out.println(str + y);
			z = x + 1;
			while (z < y) {
				if (x == 1) {
					z = y;
				} else {//用正则把相应的x替换成z
					String str1 = "" + x, str2 = "" + z;
					Pattern p = Pattern.compile(str1);
					Matcher m = p.matcher(str);
					System.out.println(m.replaceAll(str2) + y);
					z++;
				}
			}
			x++;
		}
	}
}

 

 

用递归:

import java.util.Scanner;

public class HiLo {

	public static void main(String[] args) {

		int x, y, z = 1;//x为随机数 y为输入数 z为是否猜对的监视器
		String str = "y";//控制程序总循环

		Scanner scan = new Scanner(System.in);//输入数字用
		Scanner scan1 = new Scanner(System.in);//输入字符串用

		while (str.equalsIgnoreCase("y")) {//程序总循环

			x = (int) (Math.random() * 100 + 1);//产生随机数字
			System.out.println("猜猜看,数字是多少?");
			y = scan.nextInt();

			if (y > 0 && y < 101) {//数字输入正确
				while (z != 0) {
					if (y == x) {
						System.out.println("恭喜你猜对了!!");
						z = 0;
					} else {//判断大小
						if (y > x) {
							System.out.println("再小点~");
						} else {
							System.out.println("再大点~");
						}
						System.out.println("猜猜看,数字是多少?");
						y = scan.nextInt();
					}
				}
			} else {//数字输入错误
				System.out.println("输入数字错误,必须大于0小于等于100");
				System.out.println("程序重新启动中");
				System.out.println();
			}
			if (y == x) {//控制总循环
				System.out.println("继续吗?(Y/N)");
				str = scan1.nextLine();
			}
		}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics