Question

In: Computer Science

Java Asks the user to enter a binary number ,example: 1011011 Validates that the entry is...

Java

  1. Asks the user to enter a binary number ,example: 1011011
  2. Validates that the entry is a binary number. Nothing but a binary number should be allowed.
  3. The program converts and displays the binary number to its base 10 equivalent, Example 1112 = 710
  4. The user must be asked if he/she wants to continue entering numbers or quit.
  5. 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:
Sample Output

You entered 111

Its base 10 equivalent is 7

  1. No infinite loops, examples include:
    1. for(;;)
    2. while(1)
    3. while(true)
    4. do{//code}while(1);
  2. No break statements to exit loops
  3. No labels or go-to statements
  4. If you violate any of these restrictions, you will automatically get a score of ZERO!

SPECIFIC RESTRICTIONS FOR THIS ACTIVITY

You should develop your own method, do not use Integer.parseInt (String s, int radix)

*********************************************************************************************************************************

This is my code so far, it works but once I ask the user to try another binary. The Binary doesn't come out right

***********************

import java.util.Scanner; // Needed for the Scanner class
import java.io.*; // Needed for File I/O classes

public class Binary
{
public static void main(String[] args) throws IOException
{

   String userEntry; // To hold the userEntry
   String again = "y";
   int binary = 0;
   int bin = 0;
   int decimal = 0;
   int i = 0;


// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

   PrintWriter outputFile = new PrintWriter("outDataFile.txt");

   while (again.equalsIgnoreCase("y"))
{


        // Get the user's name.
           System.out.println("Enter a Binary String: ");
           userEntry = keyboard.nextLine();
           System.out.println("\nYou entered the number: " + userEntry );
           outputFile.println("You entered the number: " + userEntry);

           //validate userName
           userEntry = checkUserEntry (userEntry);
           binary = Integer.parseInt(userEntry);
           boolean result = isBinary(binary);

           if(result == true)
      {
           bin = binary;

           while(binary != 0)
       {
           decimal += (binary%10)*Math.pow(2, i++);
           binary = binary /10;

       }
           System.out.println("its base 10 equivalent of " + bin +" is " + decimal );
           outputFile.println("its base 10 equivalent of " + bin +" is " + decimal );
       }
       else
       {
           System.out.println("This is not a Binary Number, try again");
       }

       System.out.println("\n\nWould you like to try another number? (y/Y). Anything else will quit");
       again = keyboard.nextLine();

      }
      outputFile.close();
      System.out.println("Goodbye");

}//end main


   public static boolean isBinary(int binary)
   {
       int Input = binary;
           while (Input != 0)
               {
                   if (Input % 10 > 1)
                   {
                       return false;
                   }
           Input = Input / 10;
               }
                       return true;
   }

public static String checkUserEntry (String userAnswer)
{

   int userAnswerLength = userAnswer.length();
   int counter = 0;//to iterate through the string
   // Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

   while(userAnswerLength==0)
   {
               System.out.println("That is not a number >= 0, try again");
               userAnswer = keyboard.nextLine();
               userAnswerLength = userAnswer.length();
       }

   while(counter < userAnswerLength)
   {
           if(!Character.isDigit(userAnswer.charAt(counter)))
           {
               System.out.println("That is not a number >= 0, try again ");
               userAnswer = keyboard.nextLine();
               userAnswerLength = userAnswer.length();
               counter = 0;
           }
           else
           {
               counter++;
           }
           while(userAnswerLength==0)
           {
                  System.out.println("That is not a number >= 0, try again");
                   userAnswer = keyboard.nextLine();
                   userAnswerLength = userAnswer.length();
           }
       }

       return userAnswer;
}

}//end class ValidateUserName

Solutions

Expert Solution

SOLUTION:

There were 2 problems in the following code:

if(result == true)
{
bin = binary;

while(binary != 0)
{
decimal += (binary%10)*Math.pow(2, i++);
binary = binary /10;

}

decimal variable should be reset to 0 before starting next binary number. Similarly i should be reset to 0 before starting conversion.

With fix code will be:

if(result == true)
{
bin = binary;
decimal = 0;
i = 0;

while(binary != 0)
{
decimal += (binary%10)*Math.pow(2, i++);
binary = binary /10;

}

Other thing I noticed there is a note given for not to use parseInt method, but your code still uses it.

To avoid parseInt method use, changed the code to use String input only.

Solution is to parse the string character by character and to convert character to its equivalent integer value subtract '0' from character. The result will be the digit.

Changed the isBinary() method to use String input only to validate if the number entered is valid binary input or not.

CODE:

import java.util.Scanner; // Needed for the Scanner class
import java.io.*; // Needed for File I/O classes

public class Binary
{
public static void main(String[] args) throws IOException
{
String userEntry; // To hold the userEntry
String again = "y";
int binary = 0;
int bin = 0;
int decimal = 0;
int i = 0;

// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

PrintWriter outputFile = new PrintWriter("outDataFile.txt");

while (again.equalsIgnoreCase("y"))
{
// Get the user's name.
System.out.println("Enter a Binary String: ");
userEntry = keyboard.nextLine();
System.out.println("\nYou entered the number: " + userEntry );
outputFile.println("You entered the number: " + userEntry);

//validate userName
userEntry = checkUserEntry (userEntry);
boolean result = isBinary(userEntry); // pass the string only
  
int length = userEntry.length();
int index = 0;

if(result == true)
{
bin = binary;
decimal = 0; //reset decimal
i = 0; // reset i to 0
index = length - 1;

while(length-- != 0) // loop till length becomes 0
{
decimal += ((userEntry.charAt(index--) - '0') % 10) * Math.pow(2, i++); // subtract '0' to get integer value

}
System.out.println("its base 10 equivalent of " + userEntry +" is " + decimal );
outputFile.println("its base 10 equivalent of " + userEntry +" is " + decimal );
}
else
{
System.out.println("This is not a Binary Number, try again");
}

System.out.println("\n\nWould you like to try another number? (y/Y). Anything else will quit");
again = keyboard.nextLine();
}
outputFile.close();
System.out.println("Goodbye");
}//end main


public static boolean isBinary(String binary)
{
int length = binary.length();
int index = length - 1;
while (length-- != 0) // loop till length becomes 0
{
if ((binary.charAt(index--) - '0') % 10 > 1) // extract character and subtract '0' to get integer value
{
return false;
}
}
return true;
}

public static String checkUserEntry (String userAnswer)
{

int userAnswerLength = userAnswer.length();
int counter = 0;//to iterate through the string
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

while(userAnswerLength==0)
{
System.out.println("That is not a number >= 0, try again");
userAnswer = keyboard.nextLine();
userAnswerLength = userAnswer.length();
}

while(counter < userAnswerLength)
{
if(!Character.isDigit(userAnswer.charAt(counter)))
{
System.out.println("That is not a number >= 0, try again ");
userAnswer = keyboard.nextLine();
userAnswerLength = userAnswer.length();
counter = 0;
}
else
{
counter++;
}
while(userAnswerLength==0)
{
System.out.println("That is not a number >= 0, try again");
userAnswer = keyboard.nextLine();
userAnswerLength = userAnswer.length();
}
}

return userAnswer;
}
}//end class ValidateUserName

OUTPUT:

outDataFile.txt


Related Solutions

Java Program 1. Write a program that asks the user: “Please enter a number (0 to...
Java Program 1. Write a program that asks the user: “Please enter a number (0 to exit)”. Your program shall accept integers from the user (positive or negative), however, if the user enters 0 then your program shall terminate immediately. After the loop is terminated, return the total sum of all the previous numbers the user entered. a. What is considered to be the body of the loop? b. What is considered the control variable? c. What is considered to...
Write a Java program that asks the user to enter an integer that is used to...
Write a Java program that asks the user to enter an integer that is used to set a limit that will generate the following four patterns of multiples of five using nested loops •Ascending multiples of five with ascending length triangle •Ascending multiples of five with descending length (inverted) triangle •Descending multiples of five with ascending length triangle •Descending multiples of five with descending length (inverted) triangle Use error checking to keep asking the user for a positive number until...
In java, write a program that asks the user to enter a character. Then pass the...
In java, write a program that asks the user to enter a character. Then pass the character to the following methods. isVowel() – returns true if the character is a vowel isConsonant() – returns true if the character is a consonant changeCase() – if the character is lower case then change it to upper case and if the character is in upper case then change it to lower case. (return type: char) Example output is given below: Enter a character...
Write a program that asks the user to enter an unsigned number and read it. Then...
Write a program that asks the user to enter an unsigned number and read it. Then swap the bits at odd positions with those at even positions and display the resulting number. For example, if the user enters the number 9, which has binary representation of 1001, then bit 0 is swapped with bit 1, and bit 2 is swapped with bit 3, resulting in the binary number 0110. Thus, the program should display 6. COMMENT COMPLETE CODE PLEASE
Develop a program that asks a user to enter the number 10, and then it outputs...
Develop a program that asks a user to enter the number 10, and then it outputs COUNT-DOWN from 10 to 0. using for-loop
Develop a program that asks a user to enter the number 10, and then it outputs...
Develop a program that asks a user to enter the number 10, and then it outputs COUNT-DOWN from 10 to 0.
Write a program (polygon.py) that asks the user to enter the number of sides in a...
Write a program (polygon.py) that asks the user to enter the number of sides in a regular polygon. For example, an equilateral triangle is a regular 3-sided polygon, a square is a regular 4-sided polygon, and a pentagon is a regular 5-sided polygon. If a user enters a number of sides between 3 and 25, inclusive, draw the polygon and wait for the user to click on the screen to quit the program. If the user enters a number less...
Program should be written in Java a) Write a program that asks the user to enter...
Program should be written in Java a) Write a program that asks the user to enter the approximate current population of India. You should have the computer output a prompt and then YOU (as the user should enter the population.)  For testing purposes you may use the value of 1,382,000,000 from August 2020. Assume that the growth rate is 1.1% per year. Predict and print the predicted population for 2021 and 2022. The printout should include the year and the estimated...
USING THE SWITCH STATEMENT - Write a java program that asks the user to enter the...
USING THE SWITCH STATEMENT - Write a java program that asks the user to enter the number of their favorite month of the year – obviously, that would be 1 – 12. Write a switch statement that takes the number and converts it to the fully spelled out name [ex. 3 would be MARCH] . Be sure to build in error message to catch any invalid data entries such as 0 or 13 etc. Print out the number that was...
Python. Write a code that asks the user to enter a string. Count the number of...
Python. Write a code that asks the user to enter a string. Count the number of different vowels ( a, e, i, o, u) that are in the string and print out the total. You may need to write 5 different if statements, one for each vowel. Enter a string: mouse mouse has 3 different vowels
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT