查表法就是利用数组的下标,给你两个例子:
- //需求:练习数组的查表法,查出是星期几
- import java.util.*;//导入包
- class ArrayDemo6
- {
- public static void main(String[] args)
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("请在下面输入星期数");
- int week = sc.nextInt();
- if (week <= 0 || week >7)
- {
- System.out.println("星期数输入错误");
- return;
- }
- //查表法输出星期数
- String[] arr = {"","星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
- System.out.println(arr[week]);
- }
- }
复制代码
- //需求:用查表法把十进制转换成二进制、八进制、十六进制
- class ArrayDemo8
- {
- public static void main(String[] args)
- {
- System.out.println(toBin(6)+"\n"+toOct(60)+"\n"+toHex(60));
- }
- public static void toBin(int num)
- {
- trans(num,1,1);
- }
- public static void toOct(int num)
- {
- trans(num,7,3);
- }
- public static void toHex(int num)
- {
- trans(num,15,4);
- }
- public static char trans(int num,int base,int offset)
- {
- if (num == 0)
- {
- return 0;
- }
- char[] c ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
- char[] arr = new char[32];
- int pos = arr.length;
- while (num != 0)
- {
- int temp = num & base;
- arr[--pos] = c[temp];
- num = num >>> offset;
- }
- char[] c1 = new char[arr.length-pos];
- for (int i = pos;i < arr.length;i++)
- {
- c1 = arr[i];
- }
- return
- }
- }
复制代码 |