I need help completing a Java with NetBeans program, which has the user interfac
ID: 3663301 • Letter: I
Question
I need help completing a Java with NetBeans program, which has the user interface already in place, that converts an eight bit two's complementary binary number to a decimal integer. Defining a binary number as int binNum[8]. I have to convert the eight characters in line to eight integers in the binNum array and verify that each bit entered by the user is 0 or 1 and output an error message if it is not. If the user enters 11111101 the output to the console should be 11111101 (bin) = -3 (dec) this is the code i need to complete
public void actionPerformed(ActionEvent event) {
int[] binNum = new int[8]; String line = textField.getText();
if (line.length() == 8) {
// COMPLETE
} else {
System.out.printf("Enter exactly eight bits. ");
}
}
}
Explanation / Answer
Here is the code for you.
public void actionPerformed(ActionEvent event) {
int[] binNum = new int[8]; String line = textField.getText();
if (line.length() == 8) {
for(int i = 0; i < 8; i++)
{
char bit = line.charAt(i);
if(bit == '0')
binNum[i] = 0;
else if(bit == '1')
binNum[i] = 1;
else
{
System.out.printf("The given number is not binary number. ");
break;
}
}
int i = 8;
int [] num = new int[8];
do
{
i--;
}while(num[i]==0);
i--;
while(i!=-1)
{
if(num[i] == 0)
num[i] = 1;
else
num[i] = 0;
i--;
}
int number = 0;
for(i = 7; i >= 0; i--)
number += java.lang.Math.pow(2, 7-i) * num[i];
number *= -1;
System.out.println("The number is: "+number);
}
else {
System.out.printf("Enter exactly eight bits. ");
}
}
}
If you have any further queries, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.