# Thread: Algorithm for converting binary/hex to decimal

1. Member
Join Date
Nov 2010
Posts
2
Rep Power
0

## Algorithm for converting binary/hex to decimal

We were asked to convert hex/bin to dec without using the parseInt parseDouble through the Scanner class.

I started using the switch statement. My problem is that I don't know how to loop the number of inputs in the scanner class, since every input out of 6 inputs would have to undergo the process of conversion. I'm trying a while loop but I still cant get it. Second, i tried a switch statement to link to the methods of conversion to the input but it still doesnt work. please help!

for(int i=1; i<=6; i++){
if(i<=6){
String num = s.nextLine();
String number = num(i).substring(0, num(i).length()-3);
char each = num(i).charAt(num(i).length()-1);

switch(each){
case 'b': System.out.println(c.binToDecimal(num));
break;
case 'h': System.out.println(c.hexToDecimal(num));
break;
default: System.out.println ("Inconvertible. Please try again. :s");
}
}
else{
System.out.println("------------------");
}
}

Java Code:
`                    String number = num(i).substring(0, num(i).length()-3);`
That's one hell of an (incorrect) expression. You were trying a top down approach to your problem and you ended up with an entirely different problem. Try a bottom up approach and try to implement those binToDec( ... ) and hexToDec( ... ) methods first. If needed you can do all sorts of fancy input later.

kind regards,

Jos

3. Member
Join Date
Nov 2010
Posts
2
Rep Power
0
Revised it to this but it still doesnt work. Ugh!

while(s.hasNextLine()){
String m = "---";
String num = s.nextLine();
if(num.equals(m))
System.out.println("----------------------");
else{
String number = num.substring(0, num.length());
char base = num.charAt(num.length()-1);

switch(base){
case 'b': System.out.println(c.binToDecimal(num));
break;
case 'h': System.out.println(c.hexToDecimal(num));
break;
default: System.out.println ("Inconvertible. Please try again. :s");
}
}
}
}