hi there,
i'm currently writing a program to convert numbers between bases and i'm stuck in a spot. anyway, i've just truncated to the part where i'm stuck at and to simply code, values are preset here. In short, this code is suppose to convert the number 71 in base 8 to a decimal number (via Math.pow method). I don't know why it's not working as I have printed out values in intermediate steps to verify. To avoid losing values, i went on and chose instantiate product as a double (it was originally an int). The run gives product = 49.0 and 440 during the loop when it should be 1.0 and 56.0. I appreciate any feedback. Sorry about the spacing, I don't know why the editor removed the indentions.
UPDATE: found solutions, moderator please delete thread
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Do you want to convert /from decimal or /to decimal? (To quit type /exit)"); String reply = scan.nextLine(); while (!reply.equals("/exit")) { if (reply.equals("/from")) { System.out.println("Enter number in decimal system: "); int decimal = scan.nextInt(); int remainder; StringBuilder converted = new StringBuilder(); System.out.println("Enter target base: "); int base = scan.nextInt(); if (base == 2 || base == 8) { while (decimal > 0) { remainder = decimal % base; converted.insert(0, remainder); decimal = decimal / base; } } else { char[] hex = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; while (decimal > 0) { remainder = decimal % base; converted.insert(0, hex[remainder]); decimal = decimal / base; } } System.out.println("Conversion result: " + converted); } else if (reply.equals("/to")) { System.out.println("Enter source number: "); String sourceNumber = scan.next(); System.out.println("Enter source base: "); int base = scan.nextInt(); int converted = 0; converted = Integer.parseInt(sourceNumber,base); System.out.println("Conversion to decimal result: " + (int) converted); } System.out.println("Do you want to convert /from decimal or /to decimal? (To quit type /exit)"); reply = scan.next(); } } }