【问题标题】:Building a hex string from ArrayList<Integer>从 ArrayList<Integer> 构建一个十六进制字符串
【发布时间】:2017-03-28 22:54:17
【问题描述】:

我已经计算了余数,但我的问题是从余数到新的十六进制字符的实际转换。在 Dec2Hex 类中我需要做的就是从超类(我已经完成)中获取余数数组列表,然后使用字符数组 hexDigits[] 将其转换为字符串。我必须在循环中遍历剩余的数组列表并构建十六进制字符串,但我不知道该怎么做。

//this is the Binary to Decimal implementation which hex2dec is based off of

package business;

import java.util.ArrayList;

/**
 *
 * @author
 */
public class Bin2Dec implements Conversion{
    public static final String VALUEDESC ="Binary";
    public static final String RESULTDESC ="Decimal";
    private String origval, result;
    private ArrayList<String> resultsteps;
    private String emsg;
    private boolean valid;

    public Bin2Dec(String value) {
        emsg = "";
        origval = value;
        if (valid =isValid(value)) {  //valid will be true or false
            convert(value);
        } else {
            emsg = "Illegal, binary value (must be only zeros and ones";
        }
    }
    private boolean isValid(String v) {
        for (int i=0; i< v.length(); i++) {
            if (v.charAt(i) != '1' && v.charAt(i) != '0') {
                return false;
            }
        }
        return true;
    }
    // we can do isValid because we declared private boolean valid
    @Override
    public boolean isValid() {
        return this.valid;
    }
    private void convert(String v) {
        long r = 0;
        String reverse = new StringBuilder(v).reverse().toString();
        resultsteps = new ArrayList<>();
        for (int i=0; i < reverse.length(); i++) {
            if (reverse.charAt(i) == '1') {
                long p = (long) Math.pow(2,i);
                r += p;
                resultsteps.add("There is a(n) " + p + " in the number (2^" + i + ")" );
            }
        }
        this.result = String.valueOf(r);
    }
    @Override
    public String getResult() {
        return this.result;
    }
    @Override
    public ArrayList<String> getProcessLog() {
        return this.resultsteps;
    }
    @Override
    public String getErrorMsg() {
        return this.emsg;
    }
    @Override
    public String getValue() {
        return this.origval;
    }

}

实施

//this is the hex2dec implementation I created 

package business;

import java.util.ArrayList;

/**
 *
 * @author 
 */
public class Dec2Hex extends Dec2Num {
    public static final String VALUEDESC="Decimal";
    public static final String RESULTDESC="Hexadecimal";
//    private ArrayList<String> codes;
    public static final int BASE=16;
    private String binaryresult;
    char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
              'A', 'B', 'C', 'D', 'E', 'F'};
    String hex = "";

    public Dec2Hex(String value) {
        super(value, Dec2Hex.BASE);
        this.binaryresult="";  

    }


    @Override
    public String getResult() {
        if(!super.isValid()) {return "Invalid Value";}
        for(Integer i : super.getRemainders()) {                             //we deleted remainders in Dec2Bin so we call super
            String hex = Integer.toHexString(i);
            this.binaryresult += String.valueOf(i);
        }
        switch (hex) {


        }

       return this.binaryresult;
    }

//    public ArrayList<String> getHexConversion(int d) {
//        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
//              'A', 'B', 'C', 'D', 'E', 'F'};
//        String hex = "";
//        while (d > 0) {
//            int digit = d % BASE;              
//            hex = hexDigits.charAt(digit) + hex; 
//            d = d / BASE;
//        }
//    return codes;
//    }

    //    public ArrayList<String> getHexConversion(int d) {
//
//        String hex = "";
//        while (d > 0) {
//            int digit = d % BASE;             
//            char hexDigits = (hex <= 9 && hex >= 0);
//            (char)(hexDigits + '0') : (char)(hexDigits- 10 + 'A');
//        }
//    return this.binaryresult;
//    }
}

接口和抽象实现

//interface

public interface Conversion {
    public String getValue();
    public String getResult();
    public boolean isValid();
    public ArrayList<String> getProcessLog();
    public String getErrorMsg();
    //each subclass should fulfill these methods   
}

//abstract implementation

public abstract class Dec2Num implements Conversion{
    private String origval, emsg;
    private boolean valid;
    private int base;
    private ArrayList<String> resultsteps;
    private ArrayList<Integer> remainders;

    public Dec2Num(String value, int base) {  //int base b/c it needs to know what to divide down by
       emsg ="";
       origval = value;
       this.base = base;
       try {
           long n = Long.parseLong(value);
           if (n < 0 ) {
               emsg = "Bad decimal value: must be positive.";
               this.valid = false;
           } else {
              this.valid = true;
              resultsteps = new ArrayList<>();
              remainders = new ArrayList<>();
              convertByRecur(n);
           }
        } catch (NumberFormatException e) {
           emsg = "Illegal value: not a decimal integer";
           this.valid = false;
        }
    }//end of constructor
        @Override
    public boolean isValid() {
        return this.valid;
    }
    private void convertByRecur(long n) {
        int r = 0;

        r = (int)(n % this.base);
        long newval = n / this.base;
        resultsteps.add(n + " divided by " + this.base + "="
                        + newval + " w/remainder of: "  +r);

        if (newval > 0) {
            convertByRecur(newval);  //recursive call
        } 
        remainders.add(r);
    }
    @Override
    public ArrayList<String> getProcessLog() {
        return this.resultsteps;
    }
    @Override
    public String getErrorMsg() {
        return this.emsg;
    }
    @Override
    public String getValue() {
        return this.origval;
    }
    @Override
    public abstract String getResult();

    protected ArrayList<Integer> getRemainders() {
        return this.remainders;
    }
}

【问题讨论】:

  • 不要转储大量代码,而是提供 real minimal reproducible example 并给出代码失败的具体示例输入/输出。
  • 这是一大堆代码,我担心它可能会阻止一些本来想早点提供帮助的人。我们真正需要的只是来自 getResult() 的 6 行麻烦的代码和 ArrayList&lt;Integer&gt; 的声明(这将替代您的 super 调用,这也与问题无关)。

标签: java arrays arraylist interface hex


【解决方案1】:

首先,调用Integer.toHexString() 应该可以,但它绕过了hexDigits 数组的想法。唯一潜在的问题是它会给你小写字母a 虽然f 你可能想要大写的等价物。

String.valueOf(i) 不正确。如果i 是7,它将给你7,但如果i 11,它会给你11,你想要B,十六进制数字。你可以这样做

        this.binaryresult += hex;

您根本不需要您的 switch 声明。

假设您确实想使用您的 hexDigits 数组:

  • 要从数组中获取正确的char,只需使用hexDigits[i]
  • 您可以将char 直接附加到String,而无需先将其转换为String

        this.binaryresult += yourChar;
    

在提供我的代码版本之前,我会让您稍微挣扎一下。我相信你能做到。

【讨论】:

  • 我不习惯在堆栈溢出上发帖,所以感谢您的反馈!你帮了我很多 b/c Java 有时让我感到困惑;实际上,这是我自 Java 1 以来的第一次编程体验。
猜你喜欢
  • 2011-01-15
  • 2010-09-21
  • 1970-01-01
  • 2021-06-26
  • 2018-06-24
  • 2010-10-04
  • 1970-01-01
  • 2014-03-07
  • 2019-07-27
相关资源
最近更新 更多