what do i need to change if i want this program to convert decimal to hexadecimal thanks.

``````package dectooctal;

import java.util.Scanner;
public class Dectooctal {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int broj;

System.out.print("ENTER NUMBER THAT YOU WANT TO CONVERT TO OCTAL: ");
broj = input.nextInt();
convert(broj);
}
public static void convert (int a){
String obrnuti =" ";
while (a>0){
int x = a%8;
obrnuti += x;
a/=8;
}
System.out.println(reverse(obrnuti));
}
public static String reverse(String a){
String novi =" ";
for (int i=a.length()-1;i>=0; i--){
char c = a.charAt(i);
novi += c;
}
return novi;

}

}
``````
3
Contributors
2
Replies
13
Views
5 Years
Discussion Span
Last Post by deceptikon

you're making it way too difficult.
check: this, this and this, for instance.

You need to divide and modulo by 16 instead of 8, and you need to use the letters 'A' through 'F' when `x` is greater than 9. A fun trick is with a table lookup of digits:

``````public static void convert(int a){
String digits = "0123456789ABCDEF";
String obrnuti = " ";

while (a > 0){
int x = a % 16;
obrnuti += digits.charAt(x);
a /= 16;
}

System.out.println(reverse(obrnuti));
}
``````

you're making it way too difficult.

That's all well and good, but it's not unreasonable to assume that a teacher is disallowing use of the standard library for this exercise.

Edited by deceptikon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.