/** * BaseConverter * * @version 28-Ott-2006 * @author Adriano Luchetta * * copyright: not applicable * * converte numeri interi da base decimale a un'altra base n >= 2 e invia * la codifica a standard output. * Se la base e' superiore a 10 usa come cifre i caratteri a partire da 'A'. * I numeri interi e la base sono acquisiti da standard input. * */ import java.util.Scanner; public class ToGenericBaseConverter2 { public static void main(String[] args) { final String END_OF_DATA = ""; final char ELEVENTH_DIGIT = 'A'; // prompt all'operatore System.out.println("***CONVERTITORE DA BASE DECIMALE A BASE GENERICA***\n"); //Lettura da standard input Scanner in = new Scanner(System.in); boolean done = false; while (!done) { System.out.print("inserire numero e base: "); String line = ""; if (in.hasNextLine()) line = in.nextLine(); if (line.equals(END_OF_DATA)) { System.out.println("\n***FINE***"); done = true; } else { Scanner tok = new Scanner(line); int n = 0; if (tok.hasNextInt()) n = tok.nextInt(); int base = 0; if (tok.hasNextInt()) base = tok.nextInt(); tok.close(); System.out.println(n + " " + base); if (base < 2) System.out.println("base " + base + " non ammessa\n"); else { System.out.print("cifre usate in base " + base + ": "); for (int i = 0; i < base; i++) { if (i < 10) System.out.print(i); else System.out.print((char)(ELEVENTH_DIGIT + i - 10)); } System.out.println(""); int p = n; String sign = ""; if (n < 0) { sign = "-"; p = -n; } String nStr = ""; while (p > 0) { int q = p % base; if (q < 10) nStr = q + nStr; else nStr = (char)(ELEVENTH_DIGIT + q - 10) + nStr; p = p / base; } System.out.println(n + " decimale = " + sign + nStr + " in base " + base + "\n"); } } } in.close(); } }