You can use the switch case to list the actions you need to perform. The switch performs a selection-based action; you can also develop several actions. for better understanding follow this link
I did not change your conversion logic, but the decision-making process and replaced it with a switch
import java.util.Scanner; public class BinaryToDecimal { public String toBinary(int n) { if (n == 0) { return "0"; } String binary = ""; while (n > 0) { int rem = n % 2; binary = rem + binary; n = n / 2; } return binary; } public int binaryTodecimal(int i) { int n = 0; for (int pow = 1; i > 0; pow *= 2, i /= 10) n += pow * (i % 10); return n; } public static void main(String[] args) { int answer2 = 0; String answer; final int info = 10; for (int i = 0; i < info; i++) { Scanner kb = new Scanner(System.in); System.out.println("=================================="); System.out.print("Enter your choice: "); answer = kb.next(); switch (answer) { case "1":
Output
================================== Enter your choice: 1 Enter a number: 25 The 8-bit binary representation is: 11001 ================================== Enter your choice: 2 Enter a number: 11001 The decimal representation is: 25 ================================== Enter your choice: 2 Enter a number: 1000000 The decimal representation is: 64 ================================== Enter your choice: 3 Goodbye
Also: why use static for the binary ToDecimal method, but not for the binary. I did both levels of the method object. it does more since you create an object for selection. But creating an object for each choice is not necessary, you can use the same object created several times, since you do not use any member variables to do your job, see the code below
BinaryToDecimal decimalToBinary = new BinaryToDecimal(); Scanner kb = new Scanner(System.in); System.out.println("=================================="); System.out.print("Enter your choice: "); answer = kb.next(); switch (answer) { case "1": System.out.print("Enter a number: "); answer2 = kb.nextInt(); String binary = decimalToBinary.toBinary(answer2); System.out.println("The 8-bit binary representation is: " + binary); break; case "2": System.out.print("Enter a number: "); answer2 = kb.nextInt(); int n = decimalToBinary.binaryTodecimal(answer2); System.out.println("The decimal representation is: " + n); break; case "3": System.out.println("Goodbye"); System.exit(0); break; }
source share