Binary Learn programming Java

Lesson:

Basic Data Types


Exercise:

Binary 11


Objetive:

Create a java program that asks the user for a decimal number and displays its equivalent in binary form. It should be repeated until the user enters the word "end." You must not use "ToString", but succesive divisions.


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		String answer;
		String result;
		do
		{
			System.out.print("Number to convert (or \"end\")? ");
			answer = new Scanner(System.in).nextLine();

			if (!answer.equals("end"))
			{
				int n = Integer.parseInt(answer);
				result = "";
				while (n > 1)
				{
					int remainder = n % 2;
					result = String.valueOf(remainder) + result;
					n /= 2;
				}
				result = String.valueOf(n) + result;
				System.out.printf("Binary: %1$s" + "\r\n", result);
			}
		} while (!answer.equals("end"));
	}
}