【问题标题】:Decimal number to Hexadecimal - Java十进制数到十六进制 - Java
【发布时间】:2020-02-09 22:14:19
【问题描述】:

我目前是一名学生,刚刚开始学习 Java。因此,对于任何严重的错误,我深表歉意! 我需要将用户输入的值(0-255)转换为十六进制数。 规则是我只能使用 Scanner 的 length() 和 charAt(idx) 方法或 next?() 方法或我在代码中使用的方法。我也不允许使用 while、for 或数组。

你能帮帮我吗?我编写了代码,我知道它不会以这种方式工作,但我不确定该怎么做。 谢谢!

import java.util.Scanner;
public class Hex {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Value?");
        int vl = input.nextInt();

        int r, n;

        String hex = "0123456789ABCDEF";

        r = vl % 16;
        n = r / 16;

        char ch1, ch2;

// Is there a way to use a sort of And-Or condition for two variables or do I need to use multiple ifs?

        if (r,n < 9) {
            r=ch1;
            n=ch2;
        }
        if (r,n > 9) {
            ch1 = hex.charAt(r);
            ch2 = hex.charAt(n);
        }

        int nr1, nr2;
        nr1 = ch2;
        nr2 = ch1;

        System.out.println("Hex = "+nr1 + "" + nr2);

    }
}

【问题讨论】:

标签: java


【解决方案1】:

你不需要所有这些语句,你只需要计算%16/16

static void toHex(int vl) {
    String hex = "0123456789ABCDEF";
    int r = vl % 16;
    int n = vl / 16;
    char ch1 = hex.charAt(n);
    char ch2 = hex.charAt(r);
    System.out.print("Hex = " + ch1 + "" + ch2 + " ");
}

关于信息:

if (r<9 && n<9) {  AND
}

if (r<9 || n<9) {  OR
}

【讨论】: