0

I am trying to write code in java that takes a binary string from the user, then using arrays(?), makes it a base 10 integer. My friend trying to help me wrote this, but there is no variable "c" and i do not have any idea what he tried to do.

 //Binary Conversion
 System.out.println("Enter a value in binary to convert to decimal");
 int binary = 
 int decimalValue = Integer.parseInt(c, 2);

Before this, i already had skeleton code and a declared keyboard scanner, so I assume that

int binary

is followed by

kbReader.nextInt();

Any help?

1
  • String c = kbReader.nextLine(). You need a String to pass to Integer.parseInt. Commented Feb 6, 2016 at 3:27

2 Answers 2

1

You can read the input as String using scanner.next(); then use the Integer parse method as you said which will take the input string and the wanted radix which is in this case =2

Sign up to request clarification or add additional context in comments.

1 Comment

System.out.println("Please enter a binary number : "); Scanner scanner=new Scanner(System.in); System.out.println("The decimal value : "+Integer.parseInt(scanner.next(),2));
1
    **//Conversion between Binary & Decimal**
    public static void main(String args[]){
    **//Binary to Decimal**
            String BtD = "10001110";
            if(isBinary(Integer.parseInt(BtD))){
                System.out.println("Binary Value is ==>> "+Integer.parseInt(BtD));
                System.out.println("Decimal Value is ==>> "+Integer.parseInt(BtD,2));
            }else{
                System.out.println("Not an binary no");
            }
    **//Decimal to Binary**     
            int DtB = 142;
            System.out.println("Decimal Value is ==>> "+DtB);
            System.out.println("Binary Value is ==>> "+Integer.toBinaryString(DtB));
        }
**//To check entered value is binary or not**
        public static boolean isBinary(int number){
            boolean status = true;
            while(true){
                if(number == 0){
                    break;
                }else{
                    int temp = number % 10;
                    if(temp > 1){
                        status = false;
                        break;
                    }
                    number = number /10;
                }
            }
            return status;
        }

2 Comments

Please, consider adding commentaries to your code. It is not always good to answer just with the code, especially with the code this large.
I'm an newbie. I should consider your words. Yeah.. # Dmitry Volkov

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.