Write a program to convert from decimal to Hexadecimal. CANNOT use Integer.toHex
ID: 3550611 • Letter: W
Question
Write a program to convert from decimal to Hexadecimal. CANNOT use Integer.toHexString(in). Program also has to check if decimal entered is possitive.This is what I have so far. Cannot figure out what I am doing wrong. When I enter 25 result comes out as 1 which is not wright.
import java.lang.*;
import java.util.Scanner;
public class FindHexString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String hex = "";
int decimal = 0;
int remainder = 0;
int quotient = 0;
System.out.print("Enter a number to be converted: ");
decimal = input.nextInt();
while (decimal > 16) {
quotient = decimal / 16;
remainder = decimal % 16;
do {
remainder = decimal % 16;
if (remainder == 10) {
hex = "A" + hex;
}
if (remainder == 11) {
hex = "B" + hex;
}
if (remainder == 12) {
hex = "C" + hex;
}
if (remainder == 13) {
hex = "D" + hex;
}
if (remainder == 14) {
hex = "E" + hex;
} else if (remainder == 15) {
hex = "F" + hex;
}
} while (decimal < 16);
decimal--;
}
System.out.print("Your number in hexadecimal is: " + hex + quotient);
}
}
Explanation / Answer
import java.lang.*;
import java.util.Scanner;
public class FindHexString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char a[ ]=new char [ ];
int decimal = 0;
int remainder = 0;
int quotient = 0;
int i=0;
System.out.print("Enter a number to be converted: ");
decimal = input.nextInt();
while (decimal > 16) {
decimal = decimal / 16;
remainder = decimal %16;
if (remainder == 10)
a[i++]='A';
if (remainder == 11)
A[i++]='B';
if (remainder == 12)
A[i++]='C';
if (remainder == 13)
A[i++]='D';
if (remainder == 14)
A[i++]='E';
if (remainder==15)
A[i++]='F';
if(remainder <10)
A[i++]='remainder'; }
for(int j=i-1;j>=0;j - -)
system.out.print(A[j]);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.