Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

help with program

Hi,

This is my first program in java, and I can't seem to get this program to run correctly. It is suppossed to translate a number into its binary equivilant, but i can only get it to produce 7 of the 8 bits in the binary string, before it goes to a fatal error. Any hints or help would be appreciated. I'm sorry its so long, I didn't want to leave anything out.

import javax.swing.JOptionPane;

//Public Class
public class testBinary
{
public static void main(String[] args)
{
// test the Binary class
Binary testObj = new Binary ();
testObj.getBin();

System.out.println(testObj.binStr);

boolean correct = testObj.checkBin();
// checks if translation was OK
if (correct)
System.out.println("hey, that worked");
else
System.out.println("oops, something is wrong");
}}

class Binary // class for binary translation

{
int numVal;
public String binStr = "";
int value;


{

// prompt user to enter value
String inputString = JOptionPane.showInputDialog (null,
"Enter a value between 0 and 255.",
"Homework 1 Input", JOptionPane.QUESTION_MESSAGE);

//convert string to int
numVal = Integer.parseInt(inputString);


if ((numVal >= 0) && (numVal <= 255))

value=numVal;

else
System.out.println ("Must enter an integer between 0 and 255");
}


public void getBin() // method to translate instance variable numVal
{
int bin;

int binPower = 128;

for (bin = 0; bin<7; bin++)// run through the loop until there are 8 characters
{
if ((value - binPower) < 0)// if a negative number is produced, the character is a 0
{
binPower =(binPower/2);
binStr = (binStr + 0); }

else if ((value - binPower) >= 0) // if it is positive, the character is a 1
{
value = (value - binPower); // subtract to get the remainder to continue testing
binPower = (binPower/2);
binStr = (binStr + 1);
}

else System.out.println ("Error");
}

} // end of getBin method



public boolean checkBin () // method to translate back from binary
// returns true if result matches original value, false otherwise
{
//take binStr and check to see if matches numVal

int finalAnswer = 0;

int binNum = 128;
int index;


for (index=0; index<7; index++)
{

if (binStr.charAt(index) == 0) // check if binary number is 0
binNum = (binNum/2);

else if (binStr.charAt(index)==1)
{
finalAnswer = (binNum + finalAnswer);
binNum = (binNum/2);
}
else System.out.println("Error!!");
}



if (finalAnswer == numVal)// check to see if the original number is equal to the final answer
// if it is print the binary number
JOptionPane.showMessageDialog(null, "The binary representation of the number you entered is" + binStr,
"Binary Number", JOptionPane.INFORMATION_MESSAGE);

else // if it is not print an error message
JOptionPane.showMessageDialog(null, "There is an error in the program.", "Error Message",
JOptionPane.INFORMATION_MESSAGE);

return checkBin (); }

}







Sign In or Register to comment.