//下面的代码实现部分全部放在了main函数中,看起来有些不清晰
package jinzhizhuanhuan2;
/*
*
* 测试成功。
* 经验:当修改了代码中的某个变量的名字是,特别注意:所有涉及到该变量的地方都要修改
* 遗漏任何一处,可能运行出错!!!
*/
import java.util.Scanner;
public class HextoOcalPrac {
private static String[]hexnum={
"0000","0001","0010","0011",
"0100","0101","0110","0111",
"1000","1001","1010","1011",
"1100","1101","1110","1111"
};
private static String[]ocanum={
"000","001","010","011",
"100","101","110","111"
};
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n=sc.nextInt();
while(n-->0){
String hex=sc.next();//查找并扫描下一个完整记录
StringBuilder sb=new StringBuilder();
int t=0;
//循环扫描hex字符串的每一个字符
//if else 语句表示扫描的字符要么为数字。要么为字母
while(t<hex.length()){
if('0'<=hex.charAt(t)&&hex.charAt(t)<='9')
sb.append(hexnum[hex.charAt(t++)-'0']);
else
sb.append(hexnum[hex.charAt(t++)-'A'+10]);
}//退出while后sb为对应的二进制字符串,接下来要3个字符为一组的处理改字符串
if(sb.length()%3==1)sb.insert(0,"00");//要保证sb的长度为3的倍数
if(sb.length()%3==2)sb.insert(0, "0");
String bina=sb.toString();
sb=new StringBuilder();//二进制的字符串一杯bina变量保留,所以要再次创建新的用来保存八进制
//开始将二进制的字符串变为8进制
for(int i=0;i<=bina.length()-3;i+=3){
String tem=bina.substring(i, i+3);
for(int j=0;j<ocanum.length;j++){
if(ocanum[j].equals(tem)){
sb.append(i);//数组的下标就是对应的八进制数
break;//找到对应的八进制数后,及时退出循环,节省运行时间
}
}
}
//接下来在输出之前需要清除八进制开头的0
int p=0;
//注意加上p<sb.length()防止越界!!
while(p<sb.length()&&sb.charAt(p)=='0')p++;
sb.delete(0, p);//这里要特别注意delete方法的使用!!!
System.out.println(sb);
}
}
}
}
//下面的代码把实现的部分封装在了两个方法中,看起来思路清晰了些
package jinzhizhuanhuan2;
import java.util.Scanner;
public class HextoOcal2Succeed {
public static String toBina(String hex){
String[]bina={
"0000","0001","0010","0011",
"0100","0101","0110","0111",
"1000","1001","1010","1011",
"1100","1101","1110","1111"
};
StringBuilder sb=new StringBuilder();
int t=0;
while(t<hex.length()){
if('0'<=hex.charAt(t)&&hex.charAt(t)<='9')
sb.append(bina[hex.charAt(t++)-'0']);
else sb.append(bina[hex.charAt(t++)-'A'+10]);
}
//不要忘了,保证sb的长度必须为3的倍数
if(sb.length()%3==1)sb.insert(0,"00");
if(sb.length()%3==2)sb.insert(0,"0");
String tem=sb.toString();
return tem;
}
public static String toOcal(String bina){
String[]ocal={//第一遍,不仔细,写漏了一个"010",程序结果错误!!!
"000","001","010","011",
"100","101","110","111"
};
StringBuilder sb=new StringBuilder();
for(int i=0;i<=bina.length()-3;i+=3){
String tem=bina.substring(i,i+3);
for(int j=0;j<ocal.length;j++){
if(tem.equals(ocal[j])){
sb.append(j);
break;
}
}
}
int p=0;
while(sb.charAt(p)=='0')p++;
sb.delete(0, p);//去除所有开头的0
return sb.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
//System.out.println(toOcal("000011110"));//测试
while(sc.hasNext()){
int n=sc.nextInt();
while(n-->0){
String hex=sc.next();//不能用nextLine()方法!!!
//System.out.println(toBina(hex));//测试
System.out.println(toOcal(toBina(hex)));//测试
}
}
}
}
//当然也可以把实现方法封装在类中,用面向对象的思想编程
测试结果