Welcome to Dream.In.Code
Getting Java Help is Easy!

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




Reversing a number

 
Reply to this topicStart new topic

Reversing a number, this class prints out my binary in reverse. I need it flipped.

ThuroRamming
post 9 Oct, 2008 - 09:27 PM
Post #1


New D.I.C Head

*
Joined: 9 Oct, 2008
Posts: 5

Alright guys, here's my problem. I have this class that converts a decimal number into a binary value. However, the result is printed in reverse. I need help on making the binary value print out correctly. I was trying to use some code involving a lot of modulus work but it got way too confusing. Here's what I have.
CODE

//
//
import java.util.Scanner;

//begin class
public class DecimalToBinary
{

  //begin main method
  public static void main( String args[])
  {

  Scanner input = new Scanner( System.in); //creates Scanner object

//defines and initializes variables
  int number = 0;
  int counter = 1;
  int p = 0;
  int g = 0;

  System.out.printf("Enter a decimal number:", number);//prompt
  number = input.nextInt();


//begin while statement
  while (number > 0)
   {

       if (number % 2 == 0)
    {
           p = 0;
           System.out.printf("%d",p);
            number = number / 2;
            counter = counter * 10;
       }

    else
    {
           g = 1;
           System.out.printf("%d", g);
           number = (number - 1)/2;
           counter = counter * 10;
    }

   }// end while statement


System.out.println();



  }// end main method

}// end class


Now, this program is for a friend of mine and it needs to be worked on REALLY soon, as it is due on the 10th by midnight i believe.

I'm almost positive it's something simple. Don't be afraid to rework the program itself if need be, but make sure you only use beginner level work. I hear the teacher is quite fussy about stuff not covered.
User is offlineProfile CardPM

Go to the top of the page

Gloin
post 10 Oct, 2008 - 02:57 AM
Post #2


On MeD.i.Cation

Group Icon
Joined: 4 Aug, 2008
Posts: 717



Thanked 46 times
My Contributions


You can either initialize an empty string and concatenate the result of your % 2 operation, like

str = "";
(loop)
a = number % 2
str = a + str
number = number / 2
(end loop)


or you can save the results in an array and print the values of the array in reversed order.
The above is only pseudo-code but it's rather simple to convert into java-code
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 11/20/08 05:31PM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month