Jump to content

converting numbers help

- - - - -

  • Please log in to reply
6 replies to this topic

#1
heartybowl

heartybowl

    Newbie

  • Members
  • PipPip
  • 17 posts
So for my homework assignment, my teacher wants us to convert a number to
binary, octal, and hex. So I asked him how I am suppose to do that and he told me to go here -> Integer (Java Platform SE 6)

Then I see this thing that says "toBinaryString" but I don't really know how to apply it. It's not very specific on how to use it.

here's what I have so far

Scanner cin = new Scanner(System.in);

System.out.print("Please enter an integer: ");
int num = cin.nextInt();
int binary = Integer.toBinaryString(num);


and it's not compiling

#2
sourlemon

sourlemon

    Programmer

  • Members
  • PipPipPip
  • 99 posts
Did you check what Integer.toBinaryString(num) returns?


#3
LuthfiHakim

LuthfiHakim

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 763 posts
Could you do the conversion by hand? If you could, then it's easy to write the codes. No need to peek other's. :)

#4
heartybowl

heartybowl

    Newbie

  • Members
  • PipPip
  • 17 posts
nevermind i fixed that problem but now i ran into a new one.

I need to tell the user to enter two integers separated by a space. for example, "234 83487".
and then I need to convert that string into numbers and then I need to add those two integers.

So this is the code that I used. It compiles fine but when i click run, it encounters an error and it is not able to convert the two strings that I enter, into two digits.

System.out.print("Enter two integers, separated by a space: ");
String integers = cin.nextLine();
double two = Double.parseDouble(integers);

help me please

#5
sourlemon

sourlemon

    Programmer

  • Members
  • PipPipPip
  • 99 posts
Don't forget you two numbers in a line. I didn't double check, but it looks the problem you have is passing in something "234 566", which Double.parseDouble didn't know how to parse. Read the first number first, parse it, then repeat it with the second one.


#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
You can also split the string:

String integers = cin.nextLine();

String[] numbers = integers.split(" ");

numbers[0] contains the first number (as string).
numbers[1] contains the second number (as string).

#7
heartybowl

heartybowl

    Newbie

  • Members
  • PipPip
  • 17 posts
thanks for the advice sourlemon. i fixed it. the problem was that I was using "nextLine" instead of just "next".

and wim DC, I think that's a little bit too advanced for me lol. My class isn't quite there yet.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users