0

I am new to java and I am working on a program that calculates a binary number to it's base 10 equivalent and saves each valid entry on a .txt file. Problem is that each entry is being overwritten that the only one that's saved is that last one entered. Can anyone point out what i'm doing wrong? and any tips on improving the syntax in general. Much appreciated.

import java.util.Scanner;
import java.io.*;

public class BinaryNum {
    public static void main(String[] args) throws IOException //for file writing
    {
        Scanner keyboard = new Scanner(System.in);
        String userEntry;// initial input by user for binary numbers

        int ValidUserEntryNum;
        int Decimal;
        boolean decision = false; //bool to let user choose to continue
        boolean bool; //variable to check if the valid string is a binary number

        //loops for when the user names a choice
        while(!decision)
        {
            //loops for when the user enters a binary number
            do {
                System.out.println("Please Enter a Binary Number: ");
                userEntry = keyboard.nextLine();

                //check to see if input is a string of numbers
                userEntry = checkEntry (userEntry);

                // convert string to int
                ValidUserEntryNum = Integer.parseInt(userEntry);

                //bool variable to see if the number is Binary
                bool = CheckIsBinary (ValidUserEntryNum);

                //check to see if the number is binary
                if (!bool)
                {
                    System.out.println("** Invalid.Input Must be a Binary number **");
                }
            } while(bool == false); //parameter for the loop (whether the number entered was binary)

            //convert binary number to decimal number
            Decimal = convert(ValidUserEntryNum);

            //display on console
            System.out.println("You Entered: " + ValidUserEntryNum);
            System.out.println("It's base 10 equivilant is: " + Decimal);
            System.out.println();

            //creates the file name
            File fileWR = new File("outDataFile.txt");
            //creates the file object
            fileWR.createNewFile();

            BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));

            //to check if there is an existing file
            if (fileWR.exists())
            {
                //writes in the file
                output.write("You Entered: " + ValidUserEntryNum +"\r\n");
                output.write("It's base 10 equivilant is " + Decimal +"\r\n");
                output.close();
            }
            else //creates a new file if one doesnt already exist.
            {
                fileWR.createNewFile();
            }

            //option if the user wants to continue
            System.out.println("Do you wish to continue?(yes or no):");
            String st = keyboard.nextLine();
            if (st.contentEquals("no"))
            {
                decision = true;
            }
        }

    }
    //to check if the user entered only a string of numbers (done)
    public static String checkEntry (String userAnswer)
    {
        int UserLength = userAnswer.length();
        int counter = 0;//to iterate through the string
        // Create a Scanner object to read input.
        Scanner keyboard = new Scanner(System.in);

        while (UserLength == 0)
        {
            System.out.println("That is a blank");
            System.out.println("Try again");
            userAnswer = null;
            userAnswer = keyboard.nextLine();
            UserLength = userAnswer.length();
        }

        while (counter < UserLength)
        {
            if (!Character.isDigit(userAnswer.charAt(counter)))
            {
                System.out.println("That is not a binary number");
                System.out.println("Try again");
                userAnswer = null;
                userAnswer = keyboard.nextLine();
                UserLength = userAnswer.length();
                counter = 0;
            }
            else
            {
                counter++;
            }
            while (UserLength == 0)
            {
                System.out.println("That is a blank, again");
                System.out.println("Try again");
                userAnswer = null;
                userAnswer = keyboard.nextLine();
                UserLength = userAnswer.length();
            }
        }
        return userAnswer;
    }

    //method to check if the entered number is binary. (done)
    public static boolean CheckIsBinary (int TrueBinary)
    {
        int temp;

        while (TrueBinary > 0)
        {
            temp = (TrueBinary % 10);
            if (temp != 1 && temp != 0)
            {
                return false;
            }
            TrueBinary = (TrueBinary/10);
        }
        return true;
    }

    //converts user binary to decimal
    public static int convert(int ValidUserEntryNum)
    {
        //creating variables to convert binary to decimals
        int temp = 0;
        int Decimal = 0;
        int power = 0;

        //Convert the binary number to a decimal number
        while (ValidUserEntryNum != 0)
        {
            temp = (ValidUserEntryNum % 10);
            Decimal += temp * Math.pow(2, power++);
            ValidUserEntryNum = (ValidUserEntryNum/10);
        } return Decimal;
    }

}
lczapski
  • 4,026
  • 3
  • 16
  • 32
ZootZoot
  • 33
  • 5

3 Answers3

1

You are creating a new FileWriter and a new BufferedWriter each time inside the loop which is not necessary. You can move it outside the loop.

To make your existing code work, change

new FileWriter(fileWR)

to

new FileWriter(fileWR, true)

The second parameter passed is the append flag. From javadocs (emphasis mine)

boolean if true, then data will be written to the end of the file rather than the beginning.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0

It looks like you have fileWR.createNewFile(); both inside and outside the check.

//creates the file name
    File fileWR = new File("outDataFile.txt");
    //creates the file object
    fileWR.createNewFile();  <--

    BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));

    //to check if there is an existing file
    if (fileWR.exists())
0

Change this line:

BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));

To:

BufferedWriter output = new BufferedWriter(new FileWriter(fileWR), true);

Because the constructor you used for FileWriter defaults to overwriting. http://tutorials.jenkov.com/java-io/filewriter.html#overwriting-vs-appending-the-file

Allison B
  • 166
  • 9