Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / February 2008

Tip: Looking for answers? Try searching our database.

Need help to convert my C++ codes to Java with GUI

Thread view: 
vampireex@hotmail.com - 23 Feb 2008 14:18 GMT
I'm currently exploring GUI with java and I've wrote a program in c++
to convert binary to decimal and a caesar cipher codes. Could anyone
help me to convert it to Java with GUI? I'd like to explore more on
GUI codings.

I've setup a GUI based on visual basic 6.0. it's uploaded on

http://img299.imageshack.us/img299/3698/fypgui1mf6.jpg

My c++ codings for both programs are as below.....

//================
//BINARY TO DECIMAL
//================
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
  string bin;
  int base = 10;
  int result = 0;
  int i;
  double power = 0;

  cout<<"Enter a binary number: ";
  getline(cin, bin);

  for (i = bin.length()-1; i >=0; i--)
  {

      result += ((bin[i]-48)*(pow(2,power)));

      power++;
  }
  cout<<"decimal = "<<result<<endl;

  system ("PAUSE");
  return 0;
}

//==============
// CAESAR CIPHER
//==============
#include <iostream>
#include <string>

using namespace std;
int main()
{
       int difference;
       string msg;
       int crypted;
       int real_difference;
       int i=0;

       cout<<"Enter the offset : ";
       cin>>difference;
       cin.get();
       if (difference > 26) //Brings back the number if above 26
       {
               real_difference = difference % 26;
       }

       else
       real_difference = difference;

       cout<<"Enter the message you want to crypt : ";
       getline(cin, msg);
       cout<<"Ciphertext: ";

               while (i<= msg.length())
               {

                       if(msg[i] == 32)
                       {
                               crypted = msg[i];
                               cout<<(char)crypted;
                               i++;
                       }

                       if ((msg[i] + real_difference) > 'z')
                       {

                               crypted = (msg[i] +
real_difference)-'z'+'a';
                       }

                       else
                       {
                               crypted = msg[i] + real_difference;
                       }

                       cout<<(char)crypted;
                       i++;

                       if(i>= msg.length())
                       break;
               }
               cout<<endl;

       system ("PAUSE");
       return 0;
}

Thanks in advance.
Jeff Higgins - 23 Feb 2008 15:30 GMT
vampireex wrote:

System.out.println(Long.valueOf(System.console().readLine("Enter a binary
number: "), 2));
Roedy Green - 23 Feb 2008 16:52 GMT
>I'm currently exploring GUI with java and I've wrote a program in c++
>to convert binary to decimal and a caesar cipher codes. Could anyone
>help me to convert it to Java with GUI? I'd like to explore more on
>GUI codings.

Have a look at the various applets I have posted with source code.
http://mindprod.com/applet/applets.html

Find one visually similar to what you want.  Cannibalise it.

GUI programs are 95% housekeeping with a few tiny methods that do the
calculation.
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Katak - 23 Feb 2008 17:49 GMT
On Feb 24, 12:52 am, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:
> On Sat, 23 Feb 2008 06:18:44 -0800 (PST), vampir...@hotmail.com wrote,
> quoted or indirectly quoted someone who said :
[quoted text clipped - 14 lines]
> Roedy Green Canadian Mind Products
> The Java Glossaryhttp://mindprod.com

alright thanks a lot =)
Katak - 23 Feb 2008 19:06 GMT
I wrote these codes below in Java and theres some problems passing the
string to do the conversion. Can anyone help me out? The c++ codes are
on the first post above. Thanks.

import java.util.Scanner;

public class BinaryToDecimal {

    public static void main(String[] args) {

          String bin;
          int base = 10;
          int result = 0;
          int i;
          double power = 0;

          System.out.println("Enter a binary number: ");
          Scanner input = new Scanner(System.in);
          bin = input.nextLine();

          for (i = bin.length()-1; i >=0; i--)
          {

              double cubed = java.lang.Math.pow ( 2, power);
              result += (( bin[i] - 48)*(cubed));

              power++;
          }

          System.out.print("Decimal = "+ result);
    }

}
Lew - 23 Feb 2008 20:04 GMT
> I wrote these codes below in Java and theres some problems passing the
> string to do the conversion. Can anyone help me out? The c++ codes are
[quoted text clipped - 7 lines]
>           String bin;
>               result += (( bin[i] - 48)*(cubed));

Review the Javadocs for String, the type of 'bin', at
<http://java.sun.com/javase/6/docs/api/java/lang/String.html>

Strings are not arrays, and cannot use the square-bracket notation ([]) to
represent parts of a String.  A String is an object that must be accessed
through its defined methods.

It seems that you are looking for String#charAt()
<http://java.sun.com/javase/6/docs/api/java/lang/String.html#charAt(int)>
but be aware that character encoding can differ, and '48' might not be the
magic number you're looking for.  Also, what if the /i/th character is not a
digit?

P.S., please use less aggressive indentation for Usenet posts.  Up to four
spaces (not TAB characters) per indent level is fine.  You can cut back on the
blank lines, too.  Easier-to-read listings are easier to answer.

Signature

Lew

Katak - 24 Feb 2008 04:44 GMT
> > I wrote these codes below in Java and theres some problems passing the
> > string to do the conversion. Can anyone help me out? The c++ codes are
[quoted text clipped - 27 lines]
> --
> Lew

Thx for the help. String#charAt(int) works great. I've completed it.
Now's the interface part.
Thomas A. Russ - 26 Feb 2008 19:37 GMT
> > public class BinaryToDecimal {
> >     public static void main(String[] args) {
> >           String bin;
> >               result += (( bin[i] - 48)*(cubed));
...
> It seems that you are looking for String#charAt()
> <http://java.sun.com/javase/6/docs/api/java/lang/String.html#charAt(int)>
> but be aware that character encoding can differ, and '48' might not be
> the magic number you're looking for.  Also, what if the /i/th character
> is not a digit?

And to help out with those problems, it would be wise to look at the
Character class, which has some nice useful methods like "isDigit" and
"digit" which will handle all of those particular issues for you.

As a general rule, there are a gazillion classes that come standard with
Java compilers, and you can save a lot of time and aggravation by using
them.  Porting your C++ algorithm can be a useful initial exercise for
gaining some familiarity with the language, but you will eventually want
to learn to write Java code, rather than C++ code in Java.

So, looking at some of the other built-in classes, you might discover
that the entire problem of BinaryToDecimal conversion is already handled
for you by the language itself:

 Integer.parseInt(inputString, 2).toString();

Signature

Thomas A. Russ,  USC/Information Sciences Institute

Jeff Higgins - 23 Feb 2008 21:17 GMT
Lew suggested the String.charAt() method but,
if this is an exercize in converting
number representations by hand
 see the comment;
else
why?YourConverter:MyConverter

import java.util.Scanner;

public class YourConverter {
 public static void main(String[] args) {

   String bin;
   int result = 0;
   double power = 0;

   System.out.println("Enter a binary number: ");
   Scanner input = new Scanner(System.in);
   bin = input.nextLine();

//See Roedy Green's mindprod site for details on
//converting binary to decimal numbers

   for (int i = bin.length(); i == 0; i--) {
     double cubed = Math.pow(2, power);
     result += ((bin.charAt(i) - 48) * (cubed));
     power++;
   }
   System.out.print("Decimal = " + result);
 }

}

Enter a binary number:
1101
Decimal = 0

public class MyConverter {

 public static void main(String[] args) {

   String hexString = "4341464542414245";
   Long dec = Long.valueOf(hexString, 16);
   String bin = Long.toBinaryString(dec);

   System.out.println(dec  + " : " + hexString);
   System.out.println(bin);

 }
}

4846231937305625157 :
4341464542414245
1000011010000010100011001
00010101000010010000010100001001000101
Roedy Green - 23 Feb 2008 22:08 GMT
On Sat, 23 Feb 2008 16:17:52 -0500, "Jeff Higgins"
<oohiggins@yahoo.com> wrote, quoted or indirectly quoted someone who
said :

> double cubed = Math.pow(2, power);

for cubed I would use  double cubed = x * x * x;

Math.pow works by taking logs and exponentials, each of which is
computed with a whacking huge polynomial approximation. With the
arithmetic method, you don't lose precision on doubles that happen to
be perfect  ints.

--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Katak - 24 Feb 2008 04:42 GMT
On Feb 24, 6:08 am, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:
> On Sat, 23 Feb 2008 16:17:52 -0500, "Jeff Higgins"
> <oohigg...@yahoo.com> wrote, quoted or indirectly quoted someone who
[quoted text clipped - 13 lines]
> Roedy Green Canadian Mind Products
> The Java Glossaryhttp://mindprod.com

Sorry. I think it was meant to be exponent since I was doing decimal =
binary * 2^1 , decimal = binary * 2*2, etc.  Named it wrongly.

Thanks a lot.
Roedy Green - 24 Feb 2008 13:51 GMT
On Sat, 23 Feb 2008 20:42:18 -0800 (PST), Katak
<vampireex@hotmail.com> wrote, quoted or indirectly quoted someone who
said :

>Sorry. I think it was meant to be exponent since I was doing decimal =
>binary * 2^1 , decimal = binary * 2*2, etc.  Named it wrongly.

In that case you can often use a loop to incrementally create a power,
especially if you need to intermediate values.

pow *= base;

You can create powers of two with left shifts.  e.g.

1 << 3 == 8
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Katak - 24 Feb 2008 04:46 GMT
> Lew suggested the String.charAt() method but,
> if this is an exercize in converting
[quoted text clipped - 52 lines]
> 1000011010000010100011001
> 00010101000010010000010100001001000101

Thanks. I've fixed a lil bit of it and it works well now. Updated
codings are as below.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class BinaryToDecimal {

  private static BufferedReader stdin= new BufferedReader(new
InputStreamReader(System.in));

  public static void main(String[]args) throws IOException{

     int result = 0;
     double power = 0;
     System.out.println("Enter a binary number: ");
     String bin = stdin.readLine();
     System.out.println("Binary = " + bin);

     for (int i = bin.length()-1; i >= 0; i--) {
        double exponent = Math.pow(2, power);
        result += ((bin.charAt(i) - 48) * (exponent));
        power++;
     }

     System.out.print("Decimal = " + result);

  }
}

//Now for the gui part >_<
Roedy Green - 24 Feb 2008 14:29 GMT
On Sat, 23 Feb 2008 20:46:10 -0800 (PST), Katak
<vampireex@hotmail.com> wrote, quoted or indirectly quoted someone who
said :

>   double exponent = Math.pow(2, power);
>         result += ((bin.charAt(i) - 48) * (exponent));
>         power++;

Shift would be more accurate and much much faster.

power = 1;
...
power <<= 1;

or even better just shift (bin.charAt(i) - '0') directly by i.

see http://mindprod.com/jgloss/shift.html
http://mindprod.com/jgloss/binary.html
http://mindprod.com/jgloss/precedence.html
http://mindprod.com/jgloss/bit.html
http://mindprod.com/jgloss/masking.html
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Thomas A. Russ - 26 Feb 2008 19:40 GMT
> On Sat, 23 Feb 2008 20:46:10 -0800 (PST), Katak
> <vampireex@hotmail.com> wrote, quoted or indirectly quoted someone who
[quoted text clipped - 4 lines]
>
> or even better just shift (bin.charAt(i) - '0') directly by i.

or even better:

  shift  Character.digit(bin.charAt(i),2)

Signature

Thomas A. Russ,  USC/Information Sciences Institute

Roedy Green - 23 Feb 2008 22:05 GMT
On Sat, 23 Feb 2008 11:06:36 -0800 (PST), Katak
<vampireex@hotmail.com> wrote, quoted or indirectly quoted someone who
said :

>I wrote these codes below in Java and theres some problems passing the
>string to do the conversion.

for all your conversion needs, see
http://mindprod.com/applet/converter.html

It will show you for example, how to convert your double to a String
you could feed to a JTextField.
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Roedy Green - 23 Feb 2008 22:41 GMT
>(pow(2,power)));

see http://mindprod.com/jgloss/floatingpoint.html#MATHPOW
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.