165k views
3 votes
Java Eclipse homework. I need help coding this

Challenge 14A - BaseConverter

Package: chall14A
Class: BaseConverter

Task: Create a program that takes user input as a decimal and converts it to either an octal, binary, or hexadecimal base:

1. Show a title on the screen for the program.
2. Ask the user if they want to run the program.
3. Create a menu for the user to choose the base to convert to.
4. Take decimal (base10) from user and print out the number in the new base.

1 Answer

7 votes

import java.util.Scanner;

public class BaseConvertor {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Welcome to Base Convertor! This program will convert numbers into different bases of your choosing.");

System.out.print("Do you still want to run the program? ");

String ans = scan.next();

if (ans.toLowerCase().equals("yes")){

System.out.println("1. Octal");

System.out.println("2. Binary");

System.out.println("3. Hexadecimal");

System.out.print("Type the number of the base you want to conver to: ");

int base = scan.nextInt();

System.out.print("Enter your number: ");

int num = scan.nextInt();

if (base == 1){

String newNum = Integer.toOctalString(num);

System.out.println(num+" in Octal is "+newNum);

}

else if (base == 2){

String newNum = Integer.toBinaryString(num);

System.out.println(num+" in Binary is "+newNum);

}

else if (base == 3){

String newNum = Integer.toHexString(num);

System.out.println(num+" in Hexadecimal is "+newNum);

}

}

else{

System.out.println("Have a good day!");

}

}

}

I hope this helps!

User Lilroo
by
5.4k points