路径选择2

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

 

要求在 输入一个整数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();
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值