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;



        }


    }

Recommended Answers

All 2 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.