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...
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...
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.
Create a Java program that asks a user to enter two file names. The program will...
Create a Java program that asks a user to enter two file names. The program will read in two files and do a matrix multiplication. Check to make sure the files exist. first input is the name of the first file and it has 2 (length) 4 5 6 7 Second input is the name of the second file and it has 2 (length) 6 7 8 9 try catch method
Design, plan, test, and write a computer program in Java that asks the user to enter...
Design, plan, test, and write a computer program in Java that asks the user to enter 1 number and a String. You will display the first n characters of the string where n is the number entered. For example, if the user enters 3 and java then you will print jav. If they enter 5 and Halloween then you print Hallo. If the user enters a number less than 0 then set the number to 0. Assume the user will...
Write a java program which asks the user to enter name and age and calls the...
Write a java program which asks the user to enter name and age and calls the following methods: printName(): Takes name as parameter and prints it 20 times using a while loop. printAge(): Takes age as parameter and prints all the numbers from 1 up to age. Write a java program that will print first 10 multiples of 3 in a single line.
1) Write Java application that asks the user to enter the cost of each apple and...
1) Write Java application that asks the user to enter the cost of each apple and number of apples bought. Application obtains the values from the user and prints the total cost of apples. 2) Write a java application that computes the cost of 135 apples, where the cost of each apple is $0.30. 3)Write a java application that prepares the Stationery List. Various entries in the table must be obtained from the user. Display the Stationary list in the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT