473,661 Members | 2,448 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

decimal to binary converter(java)

1 New Member
Hi. I have a problem with my converter. It works fine. the only problem is that it doesnt convert single digit numbers properly.
Expand|Select|Wrap|Line Numbers
  1. public class Main {
  2.  
  3.  
  4.     /**
  5.      * @param args the command line arguments
  6.      */
  7.         public static void main(String[] args){  //throws IOException
  8.         // TO DO codestatic double toDecimal (String s)
  9.            int dec;
  10.            String bin, conv;
  11.                     int a=1;
  12.                     while (a==1)
  13.                     {
  14.            //BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
  15.            Scanner scan = new Scanner(System.in);
  16.  
  17.            System.out.println("Please enter decimal number to convert to binary" + "\n" + "maximum of 10 digits please");
  18.            bin = scan.next();
  19.            dec = Integer.parseInt(bin);
  20.            int max[] = new int[10];
  21.            int i = 0;
  22.  
  23.            if (dec/2!=0 || dec==1)
  24.            {
  25.               while(dec!=1)
  26.               {
  27.                  max[i]=dec%2;
  28.                  dec = dec/2;
  29.                  i++;
  30.                }
  31.                  max[i]=1;
  32.             }
  33.                     System.out.print("The binary equivalent is "  );
  34.             for (int z=i; z>0; z--)
  35.             {
  36.                System.out.print(max[z]);
  37.             }
  38.  
  39.                    System.out.println("\n" + "Enter 1 for enter another value or 0 to exit:");
  40.                           String reply=scan.next();
  41.                     int b=Integer.parseInt(reply);
  42.                      if(b==1)
  43.                     a=1;
  44.                     else
  45.                     a=0;
  46. }
  47. }
  48. }
Sep 7 '08 #1
2 7035
Nepomuk
3,112 Recognized Expert Specialist
Actually, it doesn't work fine. For example, if I enter "10", it will give me "101" as the output. (Same result for "11" by the way.) Now, "101" is 1*2^0 + 0*2^1 + 1*2^2 = 1 + 0 + 4 = 5. The output you want is 1*8 + 0*4 + 1*2 + 0*1 = (1010)binary.

So, go through your code again and try to get it right.

Greetings,
Nepomuk
Sep 8 '08 #2
chaarmann
785 Recognized Expert Contributor
What do you want to achieve with:
Expand|Select|Wrap|Line Numbers
  1. if (dec/2!=0 || dec==1) 
  2. {
  3.  ... // convert
  4. }
???
You wrote: I am dividing dec by 2 (for whatever unknown reason) and if the result is not 0, then I convert. That is a complicated way of saying: I skip conversion if the user entered 0 or 1 or -1 as dec! Why did you write that? That doesn't make any sense to me. Then the if-expression goes on with: Or I convert when the user entered dec=1. But you want the opposite: when he entered 1 you want not to convert (but to restart or whatever).
That's quite contradictionar y if the user entered "1": first expression says: skip conversion and second says: do it. And if you concatenate that with "or", you alway do it. And as a result this condition prevails: skip conversion if user entered -1 or 0, else do it. I assume that instead you want to skip conversion if the user has entered a 0 or 1, because in this case you don't want to convert, but exit or restart.
So why did you not simply write it in an intuitive and easy way as
Expand|Select|Wrap|Line Numbers
  1. if (dec!=0 && dec !=1) convert
?

Is this a program from your teacher that you should debug for learning purposes, or did you write it of your own? If you wrote if of your own, what was in your mind? How did you plan in which way it should work?

By answering these questions you will find the solution to your problem.
Sep 9 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

5
9409
by: T K | last post by:
Anyone aware of such a converter? Anyone know why SUN is not all over it? tia -t
1
3310
by: Ray Mitchell | last post by:
Hello, I have two Java applications that exchange serialized objects. Although I would like to ultimately convert both to C# it's a pretty monumental task, especially for someone just learning both langauges. I thought it might be more reasonable to start with simply converting the simpler one of the two and getting it to work. I have used Microsoft's free Java to C# converter to convert most of the code, but of course I must...
3
7371
by: Brian Henry | last post by:
Does anyone know of or know how to convert a COBOL packed decimal in a text file to a decimal that .NET can work with? we are importing Old COBOL data files that have packed data in them and need to convert it to a form we can use. thanks!
26
3225
by: Christoph Zwerschke | last post by:
You will often hear that for reasons of fault minimization, you should use a programming language with strict typing: http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html I just came across a funny example in which the opposite is the case. The following is a binary search algorithm in Java. It searches a value in an ordered array a of ints: public static int binarySearch(int a, int key) {
5
3568
by: ria3 | last post by:
Hi, I have to write a program that will alow the user to specify a number (decimal, binary, or hexadecimal) and a base to convert to (decimal, binary, or hexadecimal) using subroutine methods and menu - so that the user can choose their options. I know how to convert with these number systems on paper using a pencil. However, I am not sure how to covert them in a java program. (I am using ready to program). Is there a formula I could use?...
4
2396
by: javamonster | last post by:
guys i need a help... i wanna write a java programmee to display the binary number of the entered decimal number. for ex : in t text area u should type a desimal number and press "Convert" button to display its binary in the next txt field need help mates, p.s : should use only 1 statement; stack
14
26806
realin
by: realin | last post by:
hi guys i am trying to make a program to convert decimal number into binary .. i am able to do that, but the number comes inverted.. like 1101 comes like 1011 now how do i swap it off.. here is teh code import java.io.DataInputStream;
6
13555
by: mearvk | last post by:
Does C++ or C have something roughly equivalent to this: http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html What I need is a way to quickly convert between decimal and binary and from char*/string to a numeric representation. Thanks!
4
1786
by: Yonih | last post by:
So I am trying to get this Calculator to work. It needs to take in a vaule, and select a shipping Everythin works great except the shipping part. I need it to take the shipping value and add it to the "Downpayment" and also the "Total amount paid" Example: item cost $20.00 , $8.50 shipped selected, Payment 1 = 12 + 8.50 so $20.50 Payments 2-5 = $2.00 Final Payment = $28.50
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8754
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8630
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4343
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2760
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1984
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1740
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.