Results 1 to 3 of 3
- 11-29-2010, 03:47 PM #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("------------------");
}
}
- 11-29-2010, 05:58 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,422
- Blog Entries
- 7
- Rep Power
- 29
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,
JosBuild a wall around Donald Trump; I'll pay for it.
- 11-29-2010, 07:49 PM #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");
}
}
}
}
Similar Threads
-
Converting whole number into decimal
By jim01 in forum New To JavaReplies: 2Last Post: 09-23-2010, 08:58 PM -
how to convert decimal value into 8-bit binary value
By tOpach in forum New To JavaReplies: 4Last Post: 10-26-2009, 11:17 PM -
Convert binary into decimal
By WarmRegards in forum New To JavaReplies: 8Last Post: 10-18-2009, 03:32 PM -
converting a decimal to an int
By shuks in forum New To JavaReplies: 9Last Post: 10-12-2009, 10:41 AM -
converting decimal to binary value using recursion in java
By Anindo in forum New To JavaReplies: 3Last Post: 07-25-2009, 02:44 PM
Bookmarks