when entering a negative number it does not come up with the correct answer all
ID: 3663535 • Letter: W
Question
when entering a negative number it does not come up with the correct answer all the time. Any ides on how to fix this?
import java.util.*;
import java.lang.Math;
public class BinaryToDecimal {
public static void main (String [] args){
Scanner keyIn = new Scanner(System.in);
int response;
// menu options to choose how to run the program and continue running the
// program until user decides to quit.
do{
System.out.println("Enter 1 to convert decimal to binary");
System.out.println("Enter 2 to convert binary to decimal");
System.out.println("Enter 3 to quit");
System.out.print("Please enter your choice: ");
response = keyIn.nextInt();
//choosing 1 uses case 1 for decimal conversion and 2 for binary conversion
switch(response)
{case 1:
System.out.println("");
System.out.print("Enter a whole number between -128 and +127: ");
int decimal = keyIn.nextInt();
while(decimal < -128 || decimal > 127)
{
System.out.print("Enter a whole number between -128 and +127: ");
decimal = keyIn.nextInt();
}
System.out.println("");
System.out.print(decimal + " converted into a binary is: ");
decConvert(decimal);
System.out.println("");
break;
case 2:
System.out.println("");
System.out.println("Enter a 8-bit binary number:");
String a = keyIn.next();
System.out.println("");
System.out.println(a + " converted into a decimal is: ");
int i = binconvert(a);
System.out.println(i);
break;
default:
break;
}
System.out.println("");
}while(response!=3);
System.out.println("The program has ended");
}
//method to convert from decimal to binary
public static void decConvert(int num){
String out = "";
if(num >= 0)
{
while(num > 0){
out += num % 2;
num = num/2;
}
int length = out.length();
while(length < 8){
out += 0;
length++;
}
String temp = "";
int y = 7;
//Start from right of string moving to left
while(y > -1){
temp += out.charAt(y);
y--;
}
System.out.print(temp);
}
else
{
num *= -1;
while(num > 0){
out += num % 2;
num = num/2;
}
int length = out.length();
while(length < 7){
out += 0;
length++;
}
out += 1;
String temp = "";
int y = 7;
//Start from right of string moving to left
while(y > -1){
temp += out.charAt(y);
y--;
}
System.out.print(temp);
}
}
//method to convert from binary to decimal
private static int binconvert(String a)
{
double j = 0;
for(int i = 0; i<a.length(); i++)
{
if(a.charAt(i)== '1')
j=j+ Math.pow(2, a.length()-1-i);
}
if(j > 128)
j = 128 - j;
else if(j == 128)
j = -128;
return (int) j;
}
}
Explanation / Answer
please use a simpler code to avoid confusion.Your code is too messed up with less clarity.I hope this code makes it simple for you and helpes you to implement your operations.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.