package javaxgp.teacher.test; import java.math.BigInteger; import java.util.Scanner; import java.util.TreeSet; /** * java課第一次做業 */ public class Demo1 { public static void main(String[] args) { /** *進制轉換 */ // method1(); /** * 尋找素數 */ // method2(); /** * 計算PI */ // method3(); /** * 排序問題 */ method4(); /** * 5,傻瓜操作,略 */ } private static void method4() { TreeSet<Integer> treeSet = new TreeSet(); Scanner scanner = new Scanner(System.in); for(int i = 0;i < 10;i++) { System.out.println("請輸入第" + (i + 1) + "個整數"); treeSet.add(scanner.nextInt()); } for (Integer out : treeSet) { System.out.println("排序結果:"); System.out.print(out + "\t"); } } private static void method3() { double pi=0.0d; for(int i=1;i<=1000000;i++) { pi+=Math.pow(-1,(i+1))*4/(2*i-1); } System.out.println("近似pi = " + pi); System.out.println("math庫的pi = " + Math.PI); System.out.println("偏差值(pi - Math.PI) " + (pi -Math.PI)); } private static void method2() { BigInteger init = BigInteger.ONE; while ((init = init.nextProbablePrime()).compareTo(new BigInteger("1000")) == -1) { System.out.println(init); } } private static void method1() { try { long input = 0; String num2 = null; String num8 = null; String num10 = null; String num16 = null; Scanner scanner = new Scanner(System.in); while(true) { System.out.println("請輸入要轉換的數字(輸錄字母q退出使用):"); String str = scanner.nextLine(); if("q".equals(str)) { break; } System.out.println("該數字的進製爲(2,10,8,16):"); int num = scanner.nextInt(); if(!str.isEmpty()) { switch (num) { case 2:input = Long.parseLong(str, num);break; case 8:input = Long.parseLong(str, num);break; case 10:input = Long.parseLong(str, num);break; case 16:input = Long.parseLong(str, num);break; } num2 = Long.toBinaryString(input); num8 = Long.toOctalString(input); num10 = Long.toString(input); num16 = Long.toHexString(input); System.out.println("該數字的2進製爲:" + num2); System.out.println("該數字的8進製爲:" + num8); System.out.println("該數字的10進製爲:" + num10); System.out.println("該數字的16進製爲:" + num16); } } }catch (Exception e) { System.out.println("你的輸錄有誤,程序退出!"); }finally { System.out.println("歡迎你的再次使用!"); } } }