Reputation: 13
I'm currently a student and I just started to learn Java. So I'm sorry for any terrible mistake! I need to turn a value inputed by the user (0-255) into a hexadecimal number. The rules are that I can only use length() and charAt(idx) methods or next?() method of Scanner or the ones that I've used in my code. I'm also not allowed to use while's, for's or arrays.
Can you help me out? I wrote the code and I know that it won't work this way but I'm not sure of what to do. Thank you!
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);
}
}
Upvotes: 1
Views: 89
Reputation: 54148
You don't need all these statements, you just need to compute %16
and /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 + " ");
}
And for info :
if (r<9 && n<9) { AND
}
if (r<9 || n<9) { OR
}
Upvotes: 1