Since this is homework, I can't use built-in functions. I have to use algorithms in Java.
This is what I have so far but it is wrong.
import java.util.Scanner;
public class ChangingFigures {
public static void main (String开发者_高级运维[] args){
Scanner scanner = new Scanner (System.in);
System.out.print("Enter an integer between 0 and 127:");
int num = scanner.nextInt ();
String hex = Integer.toHexString(num);
String bin = Integer.toBinaryString(num);
// ...
}
}
The algorithm is trivial:
make an empty string
do:
prepend "n" modulo "base" to that string
divide "n" by "base"
until (n == 0)
if "base" is greater than 10 you'll need to do a little work to convert the "digits" into the letters that represent 10+
To HEX:
String HEXES = "0123456789ABCDEF";
System.out.println(HEXES.charAt((num & 0xF0) >> 4) + "" + HEXES.charAt((num & 0x0F)));
To binary
精彩评论