通用菜單_完善功能

爲通用控制檯菜單完善功能:

1. 增加“退出”功能,可以在任意位置放棄選擇

2. 增加“返回到主菜單”功能,可以在任意深度回到主菜單,而不是逐級向上。

3. 爲每個葉子節點(就是最終執行命令)增加一個整數信息,將來選擇結束時返回這個整數信息,而不是返回葉子節點的字符串。因爲不同路徑的字符串可能會是相同的內容。


import java.util.*;

public class MyTree {
	private List<Node> lst = new ArrayList<Node>();

	class Node {
		String data;
		String parent;
	}

	public void add(String parent, String child) {
		Node t = new Node();
		t.data = child;
		t.parent = parent;
		lst.add(t);
	}

	/*
	 * 得到根節點 
	 * 返回根節點總是有問題,
	 * 要好好考慮一下返回null的問題 
	 * 現在總是返回null
	 */
	public String getRoot(String x) {
		for (int i = 0; i < lst.size(); i++) {
			if (lst.get(i).data.equals(x)&&x!=null){
				x = lst.get(i).parent;
				return getRoot(x);
			}
		}
		return null;
	}

	// 得到父節點
	public String getParent(String x) {
		for (int i = 0; i < lst.size(); i++) {
			if (lst.get(i).data.equals(x))
				return lst.get(i).parent;
		}
		return null;
	}

	public List<String> getChild(String x) {
		List<String> t = new ArrayList<String>();
		for (int i = 0; i < lst.size(); i++) {
			if (lst.get(i).parent.equals(x))
				t.add(lst.get(i).data);
		}
		return t;
	}
}
import java.util.List;
import java.util.Scanner;

public class MyMenu {
	MyTree tree = new MyTree();

	public void add(String parent, String child) {
		tree.add(parent, child);
	}

	public String go(String x) {
		Scanner sc = new Scanner(System.in);

		for (;;) {
			List<String> list = tree.getChild(x);
			if(list.isEmpty()){
				return x;
			}
			System.out.println("-----------");
			for (int i = 0; i < list.size(); i++) {
				System.out.println(i + "." + list.get(i));
			}
			System.out.println("- - - - - -");
			System.out.println("u.返回上一級");
			System.out.println("m.返回主菜單");
			System.out.println("e.退出");
			System.out.println("-----------");
			System.out.print("請輸入選擇:");

			String s = sc.nextLine();
			if(s.equals("m")){
				String x1 = tree.getRoot(x);
					x=x1;
				
				continue;
			}
			if(s.equals("e")){
				break;
			}
			if(s.equals("u")){
				String x1 = tree.getParent(x);
				if(x1 != null){
					x=x1;
				}
				continue;
			}
			try {
				String x1 = list.get(Integer.parseInt(s));
				x = x1;
			} catch (Exception e) {
				System.out.println("請重新選擇!");
			}
		}
		return "退出";
	}

	public static void main(String[] args) {
		MyMenu m = new MyMenu();
		m.add("水果", "蘋果");
		m.add("水果", "香蕉");
		m.add("水果", "葡萄");
		m.add("蘋果", "紅富士蘋果");
		m.add("蘋果", "國光蘋果");
		m.add("國光蘋果", "富強1");
		m.add("國光蘋果", "富強2");

		String t = m.go("水果");
		System.out.println("您選擇:" + t);
	}
}
Conclusion
-----------
0.蘋果
1.香蕉
2.葡萄
- - - - - -
u.返回上一級
m.返回主菜單
e.退出
-----------
請輸入選擇:0
-----------
0.紅富士蘋果
1.國光蘋果
- - - - - -
u.返回上一級
m.返回主菜單
e.退出
-----------
請輸入選擇:1
-----------
0.富強1
1.富強2
- - - - - -
u.返回上一級
m.返回主菜單
e.退出
-----------
請輸入選擇:u
-----------
0.紅富士蘋果
1.國光蘋果
- - - - - -
u.返回上一級
m.返回主菜單
e.退出
-----------
請輸入選擇:e
您選擇:退出






發佈了46 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章