Я написал программу на Java, которая преобразует числа между двоичными, восьмеричными, десятичными и шестнадцатеричными числами, включая пошаговые объяснения.
Она работает правильно, но я чувствую, что в структуре есть избыточная логика, особенно в методах преобразования.
Я реализовал это вручную в учебных целях вместо использования встроенных утилит преобразования Java.
import java.util.Scanner;
public class NumberSystemConverter2 {
private static final Scanner sc = new Scanner(System.in);
private static final int[] BASES = { 2, 8, 10, 16 };
private static final String[] NAMES = { "Binary", "Octal", "Decimal", "Hexadecimal" };
public static void main(String[] args) {
int choice;
do {
showMenu();
choice = getChoice();
exec(choice);
} while (choice != 2);
}
static void showMenu() {
System.out.print("MENU\n[1] Convert a number\n[2] Exit\nChoose an option: ");
}
static int getChoice() {
for (;;)
try {
int c = Integer.parseInt(sc.nextLine());
if (c == 1 || c == 2)
return c;
System.out.print("Invalid option. \nEnter only 1 or 2: ");
} catch (Exception e) {
System.out.print("Input mismatch. \nEnter a valid number: ");
}
}
static void exec(int choice) {
if (choice == 1)
convert();
else
System.out.println("Program terminated.");
}
static void convert() {
String val = getLn("Enter value to convert: ").toUpperCase();
int sb = getBase("Enter source base(2, 8, 10, 16): ");
int db = getBase("Enter destination(2, 8, 10, 16): ");
while (!valid(val, sb)) {
System.out.println("Invalid number for base \n" + sb);
val = getLn("Enter value to convert: ").toUpperCase();
}
if (sb == db) {
System.out.println("\nSource and destination bases are the same.\nResult: " + val + "(base " + sb + ") = "
+ val + "(base " + db + ")");
return;
}
steps(val, sb, db);
int dec = toDec(val, sb);
String res = db == 10 ? "" + dec : fromDec(dec, db);
System.out.print("Result: " + val + "(base " + sb + ") = " + res + "(base " + db + ")\n");
}
static String getLn(String msg) {
System.out.print("\n" + msg);
return sc.nextLine();
}
static int getBase(String msg) {
for (;;)
try {
System.out.print(msg);
int b = Integer.parseInt(sc.nextLine());
for (int v : BASES)
if (v == b)
return b;
System.out.println("Allowed bases are only 2, 8, 10, and 16.");
} catch (Exception e) {
System.out.println("Input mismatch. Enter a valid number.");
}
}
static boolean valid(String s, int b) {
for (char c : s.toCharArray())
if (cv(c) >= b || cv(c) < 0)
return false;
return true;
}
static int cv(char c) {
return c >= '0' && c = 'A' && c 0) {
int q = t / b, rem = t % b;
System.out.println("Step " + s + ": " + t + " / " + b + " = " + q + ", remainder " + vc(rem));
r.insert(0, vc(rem));
t = q;
s++;
}
System.out.println("\nRead remainder from bottom to top: " + r);
}
static int toDec(String s, int b) {
int r = 0, p = s.length() - 1;
for (char c : s.toCharArray()) {
r += cv(c) * pow(b, p);
p--;
}
return r;
}
static String fromDec(int n, int b) {
if (n == 0)
return "0";
StringBuilder r = new StringBuilder();
while (n > 0) {
r.insert(0, vc(n % b));
n /= b;
}
return r.toString();
}
static int pow(int b, int e) {
int r = 1;
while (e-- > 0)
r *= b;
return r;
}
}
Как уменьшить дублирование в таких методах, как toDec() и fromDec()?
Существует ли лучший объектно-ориентированный дизайн для такого типа преобразователя?>
Я написал программу на Java, которая преобразует числа между двоичными, восьмеричными, десятичными и шестнадцатеричными числами, включая пошаговые объяснения. Она работает правильно, но я чувствую, что в структуре есть избыточная логика, особенно в методах преобразования. Я реализовал это вручную в учебных целях вместо использования встроенных утилит преобразования Java. [code]import java.util.Scanner;
public class NumberSystemConverter2 { private static final Scanner sc = new Scanner(System.in); private static final int[] BASES = { 2, 8, 10, 16 }; private static final String[] NAMES = { "Binary", "Octal", "Decimal", "Hexadecimal" };
public static void main(String[] args) { int choice; do { showMenu(); choice = getChoice(); exec(choice); } while (choice != 2); }
static void showMenu() { System.out.print("MENU\n[1] Convert a number\n[2] Exit\nChoose an option: "); }
static int getChoice() { for (;;) try { int c = Integer.parseInt(sc.nextLine()); if (c == 1 || c == 2) return c; System.out.print("Invalid option. \nEnter only 1 or 2: "); } catch (Exception e) { System.out.print("Input mismatch. \nEnter a valid number: "); } }
static void convert() { String val = getLn("Enter value to convert: ").toUpperCase(); int sb = getBase("Enter source base(2, 8, 10, 16): "); int db = getBase("Enter destination(2, 8, 10, 16): ");
while (!valid(val, sb)) { System.out.println("Invalid number for base \n" + sb); val = getLn("Enter value to convert: ").toUpperCase(); }
if (sb == db) { System.out.println("\nSource and destination bases are the same.\nResult: " + val + "(base " + sb + ") = " + val + "(base " + db + ")"); return; }
steps(val, sb, db); int dec = toDec(val, sb); String res = db == 10 ? "" + dec : fromDec(dec, db); System.out.print("Result: " + val + "(base " + sb + ") = " + res + "(base " + db + ")\n"); }
static int getBase(String msg) { for (;;) try { System.out.print(msg); int b = Integer.parseInt(sc.nextLine()); for (int v : BASES) if (v == b) return b; System.out.println("Allowed bases are only 2, 8, 10, and 16."); } catch (Exception e) { System.out.println("Input mismatch. Enter a valid number."); } }
static boolean valid(String s, int b) { for (char c : s.toCharArray()) if (cv(c) >= b || cv(c) < 0) return false; return true; }
static int cv(char c) { return c >= '0' && c = 'A' && c 0) { int q = t / b, rem = t % b; System.out.println("Step " + s + ": " + t + " / " + b + " = " + q + ", remainder " + vc(rem)); r.insert(0, vc(rem)); t = q; s++; } System.out.println("\nRead remainder from bottom to top: " + r); }
static int toDec(String s, int b) { int r = 0, p = s.length() - 1; for (char c : s.toCharArray()) { r += cv(c) * pow(b, p); p--; } return r; }
static String fromDec(int n, int b) { if (n == 0) return "0"; StringBuilder r = new StringBuilder(); while (n > 0) { r.insert(0, vc(n % b)); n /= b; } return r.toString(); }
static int pow(int b, int e) { int r = 1; while (e-- > 0) r *= b; return r; } } [/code] Как уменьшить дублирование в таких методах, как toDec() и fromDec()? Существует ли лучший объектно-ориентированный дизайн для такого типа преобразователя?>