Hello, Please help write program in JAVA that asks the user to enter a binary nu
ID: 3803558 • Letter: H
Question
Hello,
Please help write program in JAVA that asks the user to enter a binary number ,example: 1011011
Program should do the following:
1) Validates that the entry is a binary number. NOTHING, BUT BINARY NUMBER SHOULD BE ALLOWED.
2) The program converts and displays the binary number to its base 10 equivalent, Example 1112 = 710
3) The user must be asked if he/she wants to continue entering numbers or quit.
4) Keeps a record in a txt file named outDataFile.txt with the history of all numbers entered and the associated results, in the following format:
You entered 111
Its base 10 equivalent is 7
You entered 1010101
Its base 10 equivalent is 85
5) Code should be commented
GENERAL RESTRICTIONS:
No infinite loops
No break statements to exit loops
You entered 111
Its base 10 equivalent is 7
You entered 1010101
Its base 10 equivalent is 85
Explanation / Answer
import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class BinaryToDecimalConverter { private static Scanner sc = new Scanner(System.in); private static Scanner fsc; public static void main(String args[]) { boolean flag = true; FileWriter fw = null; try { fw = new FileWriter("outDataFile.txt"); } catch (IOException e) { System.out.println("File not found!!!"); } do { System.out.println("Binary Number Converter"); try { convertBinaryToDecimal(fw); } catch (IOException e) { //ignore } System.out.println("Do you want to continue or quit(y/n)"); String input = sc.next(); if (!("n".equals(input) || "y".equals(input))) { System.out.println("Invalid input"); return; } if ("n".equals(input)) { flag = false; } } while (flag); if (fw != null) { try { fw.close(); } catch (IOException e) { // } } } private static void convertBinaryToDecimal(FileWriter fw) throws IOException { System.out.println("Enter the binary String"); String input = sc.next(); fw.write("you entered " + input + " "); boolean invalid = false; long number = 0; int lenth = input.length(); for (int i = lenth - 1; i >= 0; i--) { if (input.charAt(i) == '1') { number = number + (long) (Math.pow((double) 2, (double) lenth - i - 1)); } else if (input.charAt(i) == '0') { // } else { invalid = true; fw.write("Invalid input" + " "); System.out.println("Invalid input"); } } if (!invalid) { fw.write("Its base 10 equivaluent is " + Long.toString(number)+" "); // fw.write(Long.toString(number)); System.out.println(number); } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.