- Jun 13, 2010
- 68
- 0
- 0
My professor gave me this problem due tomorrow.
I am having a hard time trying to figure it out. I know he wants us to figure out if it is a binary number and then switch it to a decimal value. I just can't figure out what I'm doing wrong.
My code below, I am on step 2b)
Any help or pointers would be great. Thanks guys.
1. [5 points]
2. For each string entered by user, find if the string is a binary value.
a) Set a boolean variable to true.
b) Use a for loop with counter variable i which runs until String.length( ). Use char charAt(i) method
of String class to compare character at index i with 0 or 1. If a character is not 0 and 1 that
means the string is not binary (set boolean variable to false).
c) If the string is a valid binary value (indicated by Boolean variable), find the corresponding decimal
value. Use the method public static int parseInt(String s, int radix) of Integer class, with radix=2
and your String s. Print the binary string and the decimal value. If it not a binary value, then print a
message as shown below.
I am having a hard time trying to figure it out. I know he wants us to figure out if it is a binary number and then switch it to a decimal value. I just can't figure out what I'm doing wrong.
My code below, I am on step 2b)
Code:
//Part 2
String userString = scan.next();
boolean value = true;
for(int i=1;i<=userString.length();)
{
if(userString.charAt(i)==0 || userString.charAt(i)==1)
{
value=true;
i++;
}
else {value=false;}
if(value==true)
System.out.print(value);
}
Any help or pointers would be great. Thanks guys.