Welcome to Dream.In.Code
Become a Java Expert!

Join 150,399 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 961 people online right now. Registration is fast and FREE... Join Now!




String characters and binary numbers

 
Reply to this topicStart new topic

String characters and binary numbers

anorman
13 Mar, 2008 - 10:13 PM
Post #1

New D.I.C Head
*

Joined: 30 Jan, 2008
Posts: 14

Im trying to write a program that the user puts in a binary number (ie 1101...) and calculates the decimal value (2^0 +2^1 etc) as well display the number of ones in the code and if there are 3 ones grouped together. Also if the number is not a valid binary number (contains other numbers or any letters) it re-prompts until a binary number is put in. I think I have the calculations right but I cant find what code to use to look at each character in the string to say if its one or zero. I know how to do index of and replace but that doesnt do my any good. Also I would think to find the group of 3 ones the same code could be used (sort of like a substring) and just use an if/else statement to say if the number contains them or not.

CODE
import java.util.Scanner;

    public class BinaryToDecimal {
        public static void main(String[] args){
            Scanner keyboard = new Scanner(System.in);
                    
                        //number input by user
            String binary;

                        //something for individual characters. more of a place holder right now
            String number;

                        //value of binary number
            int binValue = 0;

                        //number of ones in the binary number
            int ones = 0;
            
            
            System.out.print("Enter a valid binary number:");
            binary = keyboard.next();
        
            //find length of number
            int length = binary.length();
            
            for (int counter = 0; counter<=length; counter++){

                //Calculations for each one in the binary number
                if (number == "1"){
                binValue = binValue +(2^counter);

                //Number of ones in the number
                ones = ones + 1;
                }

                //Separate calculations for 0's
                else if (number == "0"){
                ones = ones + 0;
                }

                //re-prompt if the number contains anything other than ones and zeros (Invalid binary number)
                else{
                    System.out.println(binary + " is not a valid binary number.");
                    System.out.print("Enter a valid binary number:");
                    binary = keyboard.next();
                }
            }
            System.out.println("Your number " + binary + " contains " + ones + "one(s)");
            System.out.println("The decimal value of " + binary + "is: " + binValue);
            
            }
    
    }


If anyone has an idea on those things mentioned above that would be awesome. Or if they know any specific methods for binary, everything I found was much more complex than this and didnt help.
Thanks
User is offlineProfile CardPM
+Quote Post

letthecolorsrumble
RE: String Characters And Binary Numbers
14 Mar, 2008 - 03:07 AM
Post #2

Student of The Sun
Group Icon

Joined: 7 Nov, 2007
Posts: 550



Thanked: 1 times
My Contributions
Try this for checking if the input is binary or not :
java

public boolean isBinary(String input) {

boolean check = true;
for(int i=0; i < input.length(); i++){
if(input.charAt(i) == '0' || input.charAt(i) == '1'){
continue;
}
else {
check = false;
break;
}
}
return check;
}


The code has not been compiled, may contain errors, but the idea is ok.

This post has been edited by letthecolorsrumble: 14 Mar, 2008 - 05:49 AM
User is offlineProfile CardPM
+Quote Post

anorman
RE: String Characters And Binary Numbers
14 Mar, 2008 - 08:36 PM
Post #3

New D.I.C Head
*

Joined: 30 Jan, 2008
Posts: 14

Okay I had trouble getting that to work but thanks. Here is what I got now

CODE
import java.util.Scanner;

    public class BinaryToDecimal {
        public static void main(String[] args){
            Scanner keyboard = new Scanner(System.in);
    
            String binary;
            int binValue = 0;
            int ones = 0;
        
            
            System.out.print("Enter a valid binary number:");
            binary = keyboard.next();
        
            //find length of number
            int length = binary.length();
            
            for (int counter = 0; counter<=length; counter++){
                //Calculations for each one in the binary number
                if (binary.charAt(counter) == '1'){
                binValue = binValue +(2^counter);
                //Number of ones in the number
                ones = ones + 1;
                }
                //Separate calculations for 0's
                else if (binary.charAt(counter)== '0'){
                ones = ones + 0;
                }
                //re-prompt if the number contains anything other than ones and zeros (Invalid binary number)
                else{
                    System.out.println(binary + " is not a valid binary number.");
                    System.out.print("Enter a valid binary number:");
                    binary = keyboard.next();
                }
            }
            System.out.println("Your number " + binary + " contains " + ones + "one(s)");
            System.out.println("The decimal value of " + binary + "is: " + binValue);
            
            }
    
    }



However I keep getting this error even when I put in a valid binary number
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at BinaryToDecimal.main(BinaryToDecimal.java:28)
User is offlineProfile CardPM
+Quote Post

letthecolorsrumble
RE: String Characters And Binary Numbers
15 Mar, 2008 - 05:36 AM
Post #4

Student of The Sun
Group Icon

Joined: 7 Nov, 2007
Posts: 550



Thanked: 1 times
My Contributions
Well, first you needed to implement the isBinary() method correctly.

Second, the error you receive is because of the for-loop condition
"counter<=length", should be counter<length; since the index of the String starts at 0 the maximum index would be length-1.

Third, (2^counter) is not what you want to do here; it is the bitwise exclusive OR operator. What you want to do is use the Math.pow(base,power) method.

So here is the changed code try to understand and learn:

CODE

import java.util.Scanner;
import java.lang.Math;

public class BinaryToDecimal {
    
    
    public static boolean isBinary(String input) {

        boolean check = true;
        for(int i=0; i < input.length(); i++){
               if(input.charAt(i) == '0' || input.charAt(i) == '1'){
                   continue;
               }
               else {
                  check = false;
                  break;
               }
        }
        return check;
    }
    
    
    public static void main(String[] args){
        Scanner keyboard = new Scanner(System.in);

        String binary;
        int binValue = 0;
        int ones = 0;  
        boolean done=false;
        System.out.print("Enter a valid binary number:");
        
        binary = keyboard.next();    
        //find length of number
        int length = binary.length();
        
        
        do {//do while loop for repeating if the input is incorrect
            
            if(isBinary(binary)) {//using isBinary(String input) method
                int exp = length-1;//exponent for calculations
                for (int counter = 0; counter<length; counter++) {//changed condition
                    //Calculations for each one in the binary number
                    
                    if (binary.charAt(counter) == '1') {
                        
                        binValue = binValue +(int) (Math.pow(2.0, exp));//using pow method                        
                        //Number of ones in the number
                        ones = ones + 1;
                        
                    }
                    
                    //Separate calculations for 0's
                    else {
                        ones = ones + 0;
                    }
                    exp--;
                }
                done = true;
            }
            //re-prompt if the number contains anything other than ones and zeros (Invalid binary number)
            else {            
                System.out.println(binary + " is not a valid binary number.");
                System.out.print("Enter a valid binary number:");
                binary = keyboard.next();                
            }
        }while(!done);        
        System.out.println("Your number " + binary + " contains " + ones + "one(s)");
        System.out.println("The decimal value of " + binary + "is: " + binValue);
        
        }
}


User is offlineProfile CardPM
+Quote Post

anorman
RE: String Characters And Binary Numbers
15 Mar, 2008 - 12:50 PM
Post #5

New D.I.C Head
*

Joined: 30 Jan, 2008
Posts: 14

Okay I changed it to Math.pow() and <=length to <length and to calculate the binary value correctly did Math.pow(2.0, length - (1+counter)) so it calculated right to left correctly and it works! Thank you for telling me what exactly I was doing wrong in my program so I could keep it the same and learn from my mistakes.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 06:55PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month