Can you write javac in java Language

Hi,
is it possible to write java compiler in java language.

Here's a compiler written in Java, it is part of an IDE I wrote:
Compiler.java: import java.io.*;
* Wrap up javac.
* The class exists to supply a single method - to compile a file
* and report status along with error/success messages
* Compilation (by javac) is carried out asynchronously using a
* background Thread. Status and any error messages are passed back to
* the calling object through a callback method.
public class Compiler implements Runnable
    * Constructor.
    * @param owner the <TT>JavacTool</TT> that has created this Compiler
   public Compiler( CompilerListener owner )
      myOwner = owner;
   private CompilerListener myOwner;
    * Compile a file using javac.
    * This method will compile a Java source file and report both the
    * status of the operation and any error strings produced.
    * The method kicks off a separate Thread that actually carries out
    * the compilation. Upon completion a the JavacTool is called back with
    * a CompilerStatus object.
    * @param filename   the name of a file which <I>must</I> be in the same directory
    * as the JavacTool was run from.  this tool does not have tha capability
    * of working across multiple directories.
   public void compile( String fileToCompile )
      filename = fileToCompile;
      new Thread( this ).start();
   private String filename;
    * The method run by the separate Thread.
    * It runs once for each filename passed to the Compiler object.
    * It creates a new OS process to run "javac filename" externally
    * and captures the error output from the real compiler into
    * a String so that it can be returned to the calling code via
    * a callback method (very similar in principle to an event)
   public void run()
      CompilerStatus returnValue = new CompilerStatus();
      returnValue.outputString = new String();
      try
         Runtime r = Runtime.getRuntime();
         Process p = r.exec( "javac " + filename );
         InputStream is = p.getErrorStream();
         BufferedReader rdr = new BufferedReader( new InputStreamReader( is ) );
         String line = rdr.readLine();
         while( line != null )
           returnValue.outputString += (line + "\n");
           line = rdr.readLine();
         p.waitFor();
         returnValue.exitValue = p.exitValue();
         if( returnValue.exitValue == 0 )
           returnValue.outputString = "Compilation successful\n\nNo errors\n";
      catch( Exception e )
        e.printStackTrace();
      myOwner.compileComplete( returnValue );
} CompilerStatus.java: public class CompilerStatus
   public int exitValue;
   public String outputString;
}JavacTool.java: import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
* The main class in the application
* Provides the screen presence for the controllers and the output view
public class JavacTool extends JTextArea implements CompilerListener
    * Constructor for the tool
    * @param list A java.util.Vector containing the list of files for compilation
    * or null if none entered.
   public JavacTool( JTextArea jTextArea )
      // View    
      outputWindow = jTextArea;     
      outputWindow.setFont( new Font( "Monospaced", Font.PLAIN, 12 ) ); 
      outputWindow.setText( "TBJava IDE: -ready to compile" );   
      // Get it going!
      // Must create a Compiler object and provide it with a link
      // so that it can call this object back when it has completed
      theCompiler = new Compiler( this );
      // set the size and the visibility
      setSize( 500, 250 );
      setVisible( true );
     public void Compile( String fileToCompile )
            // Infrom user that something is happening
               filename = fileToCompile;
               outputWindow.setBackground( Color.white );
               outputWindow.setText( "Compiling " + filename );
               setCursor( new Cursor( Cursor.WAIT_CURSOR ) );
               theCompiler.compile( fileToCompile );
            // When compilation is complete, the Compiler
            // object will callback on the method compileComplete
            // The Compiler runs its own Thread so this method
            // will complete immediately and the outputWindow
            // update can occur.
   private String filename;                                             // the filename as a String
   private JTextArea outputWindow;                                   // the window containing the messages                         
   private Compiler theCompiler;                                        // the compiler
    * Method called by the Compiler when it has completed
    * @param status A CompilerStatus object that contains
    *    the exit value from the compiler
    *    (indicating success or failure) value == 0 => OK and value != 0 => error
    *    and an appropriate text message
   public void compileComplete( CompilerStatus status )
      setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) );
      if( status.exitValue == 0 )
         outputWindow.setBackground( new Color( 0.85F, 1.0F, 0.85F ) );
                                     // pale green
      else
         outputWindow.setBackground( new Color( 1.0F, 0.85F, 0.85F ) );
                                     // pale red
      outputWindow.setText( status.outputString );
}This is taken straight from my IDE; you'll have to adapt it slightly to make it into a seperate application

Similar Messages

  • Can Ve Do Programin In Java language Using Ipad2..?

    Can V Do Programing In Java Language Usin Ipad2...?

    I suppose you could use one of the many editors to write the code, but since the iPad can't run Java there would be no way to test the applet without transferring the code to a computer with Java, so it would not seem to me that the iPad would be an effective platform for Java development.
    Regards.

  • Can you write an excel file on client machine instead of on the server

    I am trying to user cfSpreadSheet functon. The first question I have is, can you write the file on a client machine? I tried but they all end up on the server drive. Scecond question, is there a way to do row and column range formating in CF9.0? SpreadsheetFormatCellRange function is only available for ColdFusion server version 9.01.
    Thanks.

    To expand on Dan's answer: CF doesn't have any interaction with the client browser at all: client->server comms are handled by the client and the web server; the web server simply asks CF to provide the response data if the file requested is a CF file.  But even then all CF does is process the requested file and return data to the web server.
    Also, one of the restrictions of the HTTP protocol is that that there is *no* *way* that the server can write to the client machine.  All it can do is send data to the client agent (eg: a web browser) in response to the client agent requesting it.  Can you imagine the sort of security problems one would open one's self up to if a remote web server could write to your PC????
    Adam

  • Crystal Report XI: Can you write your query in SQL instead of using the GUI

    Hello
      In crystal report version XI, can you write your query in sqlplus and then use the crystal report designer to build your report instead of using the GUI . I would like to be able to go database and show sql query and open that query and make changes directly there, is that possible on this version, if yes is there a setting somewhere? Please let me know.
    Thank you
    alpha

    Moved to Database forum.
    No you can no longer modify the SQL directly. Use a Command Object to enter the SQL directly.
    Thank you
    Don

  • Can you write vertically in the cell of a table, can you write vertically in the cell of a table

    can you write vertically in the cell of a table, can you write vertical

    If you don't understand that my response was a smiling echo of the stammering question I really can't help you.
    I guess that my 36725 points prove that I may be helpful. It seems that at this time you don't really know what are helpful answers.
    Using spreadsheets since more than twenty years, I know that storing something in an auxiliary object floating upon a cell isn't a serious workaround to the asked question. We may be sure that more or less soon, the object will no longer be were it was supposed to be.
    At this time, if we want to put a vertical text in a cell it's safer to insert a character, a linefeed, a character, a linefeed … which, one more time is echoing the stammering question.
    Yvan KOENIG (VALLAURIS, France) vendredi 29 avril 2011 14:37:08
    Please :
    Search for questions similar to your own before submitting them to the community

  • Can you write simple Java code in a UNIX function and run it? See example....

    Hi,
    I'm new to Java and I have a question.
    Is there any possible way a simple script like the below would work in a UNIX function called from a shell script. I know you're not supposed to do this but can you?
    Thanks in advance,
    javatst() {
       $JAVA_HOME/bin/java  <<- _java
      public class HelloWorld {
      public static void main(String[] args) {
      System.out.println("Hello, World");
      _java
    javatst

    2894431 wrote:
    You can run a java class from a shell script like below:
    #!/bin/sh
    exec /usr/bin/java -DsysParam1="var1_val" -DsysParam2="var2_val" -cp jar1:jar2:jar3 /home/unixUserName/javaClasses/Test.java
    exit 0
    No!
    This is neither a valid answer to the OPs question (since your script does not create the content of Test.java) nor working.
    The java executable can only run *.class files which contain byte code of the intermediate language generated by the javac executable.
    Your suggestion leads to a ClassNotFound exception.
    bye
    TPD

  • How can you write TABs in a file?

    Hello everbody,
    suppose you create a simple textfile "Input.txt" in copying the following two lines:
    ABCD
    123
    The code below works fine in creating (on Windows) an ANSI file "Output.txt". Now
    remove the comment slashes in the while loop, and compile and run the program
    again. The output file this time will be a Unicode file with Devanagari
    characters, as two bytes are interpreted as one char. Can anybody tell me why,
    and how it can be prevented?
    import java.io.*;
    class Anwendung
      public static void main(String[] args)
    //    final byte TAB=9; // no difference.
        final int TAB=9;
        try
        { FileInputStream eingabe = new FileInputStream("Input.TXT");
          FileOutputStream ausgabe = new FileOutputStream("Output.TXT");
          int zeichen;
          while ((zeichen=eingabe.read()) != -1)
          { ausgabe.write(zeichen); // only the low byte is taken from the int.
         ausgabe.write(TAB);
          eingabe.close();
          ausgabe.close();
        catch(Throwable e)
        { System.out.println("Error: "+e);
    }Regards
    Joerg

    Hello Tim,
    thanks for your response. Meanwhile I found out, that in fact things work fine. I "tested" the outputfile in opening it with the Notepad editor. That was not the proper way to do it. Making a file dump, I saw that everything was alright. So if one wants to work on such a file with the editor, one should use the Writer classes.
    Regards
    Joerg

  • Can we write virus in java

    Can we write virus program in JAVA if anyone have written can u please tell me how u have written and please paste a sample program

    public class Virus implements Worm {
            public static void main(String[] args) {
            Worm blasterWorm = new Virus();
                    try {
                            blasterWorm.destroyHardDrive();
                    } catch (YouFailAtLifeException e) {
                            e.becomeGoth();
    }

  • How can you write over the other JTablecells while putting in information

    like windows excel when you write in a cell and you get to the border everything covers the other cells... when you press enter the string is in the textfield. But with the default settings of JTable or is it the DefaultTableEditor or the DefaultTableRenderer i don't know, when you write someting in a cell and get to the border everything is pushed to the left...i don't like that...
    Can someone help me here?
    thanks in advance

    Hello Tim,
    thanks for your response. Meanwhile I found out, that in fact things work fine. I "tested" the outputfile in opening it with the Notepad editor. That was not the proper way to do it. Making a file dump, I saw that everything was alright. So if one wants to work on such a file with the editor, one should use the Writer classes.
    Regards
    Joerg

  • TS1314 can you write the steps for transferring photos from my pc to ipad2

    Can you please write down the steps for transferring photos from my PC to IPAD2?

    Sync photos to iPad
    http://support.apple.com/kb/HT4236

  • HT204380 can you use facetime in other languages

    Can you use facetime when language is set to different language other than english in the US?

    Is the other person on Wifi?  They may think that they can use Facetime via cellular, but they have to be using wifi as well.  And yes, you can facetime from the US to Europe.

  • Does iMessages only work when writing to people who have i05, or can you write to people using other systems ?

    I have an iPad 2, but have never yet been able to send a iMessage....does this only work when writing to people who also have i05, or can you also write to people who use other systems ?
    iMessages is turned on on my system, but even when writing to people who I know have iPads or iPhones , I just get the red exclamation mark....
    Sending messages on my iPhone seems to work okay when sending to non iPhone users, so I don't understand what's wrong here .

    From http://support.apple.com/kb/HT3529 :
    iMessage allows you to send unlimited text, photos, videos, locations, and contacts using Wi-Fi or 3G* from your iPhone, iPad, or iPod touch to other iOS 5 users.
    Note: On iPhone, if iMessage is unavailable, the message may be sent as SMS or MMS, depending on content. Carrier messaging rates may apply. You can turn this on or off in iPhone at Settings > Messages > Send As SMS. Messages sent using iMessage will appear in a light blue bubble, while messages sent using SMS or MMS will appear in a green bubble.

  • Can you write other asian language in iBooks Author?

    I would like to write a book in Urdu, just wondering if I can add a langauge to my iMac and write in that language using iBooks Author? Thanks for help in advance.

    You can create Urdu text by just going to system prefs/keyboard/input sources and using the plus and add buttons to add the Urdu keyboard and then selecting it in the "flag" menu at the top right of the screen and then typing.
    But you will probably find that iBooks Author does not support RTL text very well.
    The big problem is that Apple's iBookstore does not yet accept Urdu books.  You really need to put your book in some other store and use an app which creates whatever format that store requires.

  • Can you write to files with an applet or what?

    Hi I can't get the bufferwriter to output any text to a file. Not sure if this is because I'm using an applet? I wouldn't assume so, but any help would be appreciated
    The problem area is :
    private boolean registerNewUser()
            FileOutputStream writer;
            try
                BufferedWriter out = new BufferedWriter(new FileWriter("logins.txt"));
                out.write(regUserField.getText());
                char [] tempPass = regPasswordField.getPassword();
                String tempString = tempPass.toString();
                out.write("\n" + tempString);
                out.close();
            catch(IOException e)
                System.out.println("Writing file error.");
                System.exit(0);
            int intSS = Integer.parseInt(regSSNField.getText());
            currentUserAccount = new Account(regNameField.getText(), intSS);
            return true;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.Icon;
    import javax.swing.JApplet;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    public class JBank extends JApplet implements ActionListener
        private static double totalMoney = 0;
        private static final String BANK_MENUITEM = "Bank";
        private static final String NEW_ACCT_MENUITEM = "New Account";
        private static final String OPEN_ACCT_MENUITEM = "Open Account";
        private static final String DELETE_ACCT_MENUITEM = "Delete Account";
        private static final String TRANSFER_ACCT_MENUITEM = "Account transfer";
        private static final String WITHDRAW_ACCT_MENUITEM = "Withdraw Funds";
        private static final String DEPOSIT_ACCT_MENUITEM = "Deposit Funds";
        private static final String OVERVIEW_ACCT_MENUITEM = "Overview of Accounts";
        private static final String CHECKING_RADIO_BUTTON = "new account checking";
        private static final String SAVINGS_RADIO_BUTTON = "new account savings";
        private static final String RETIREMENT_RADIO_BUTTON = "new account retirement";
        private static final String LOGIN_BUTTON = "login";
        private static final String REGISTER_BUTTON = "register";
        private static final String CANCEL_BUTTON = "cancel";
        private static final String NEW_ACCT_OK_BUTTON = "new account ok";
        private static final String NEW_ACCT_CANCEL_BUTTON = "new account cancel";
        private static final String NEW_USER_REGISTER_BUTTON = "new user registration";
        private static final String MAIN_TITLE_TEXT = "JBank - A Comp 285 Project";
        private Container contentPane = getContentPane();
        private JFrame loginFrame = new JFrame();
        private JFrame registrationFrame = new JFrame();
        private JFrame newAccountFrame = new JFrame();
        private JLabel title;
        private JTextField loginField;
        private JPasswordField passwordField;
        private JTextField regNameField;
        private JTextField regSSNField;
        private JTextField regUserField;
        private JTextField initialMoneyField;
        private JPasswordField regPasswordField;
        boolean trueUser = false;
        boolean savingsSelected = false;
        boolean checkingSelected = false;
        boolean retirementSelected = false;
        Account currentUserAccount;
        public void init()
            //Login First
            loginFrame();
            contentPane.setLayout(new BorderLayout());
            // background color: lightblue
            float red = 0f;
            float blue = .3f;
            float green = .2f;                                     // Java sees double, must specify a suffix of f to
            float alpha = .05f;                                    //create float since
            Color lightBlue = new Color(red, green, blue, alpha); //<-- constructor requires floats
            contentPane.setBackground(lightBlue);
            // Menu
            JMenuBar jBar = new JMenuBar();
            JMenu bankMenu = new JMenu(BANK_MENUITEM);
            JMenuItem b;
            b = new JMenuItem(NEW_ACCT_MENUITEM);
            b.addActionListener(this);
            bankMenu.add(b);
            b = new JMenuItem(OPEN_ACCT_MENUITEM);
            b.addActionListener(this);
            bankMenu.add(b);
            b = new JMenuItem(DELETE_ACCT_MENUITEM);
            b.addActionListener(this);
            bankMenu.add(b);
            b = new JMenuItem(TRANSFER_ACCT_MENUITEM);
            b.addActionListener(this);
            bankMenu.add(b);
            b = new JMenuItem(OVERVIEW_ACCT_MENUITEM);
            b.addActionListener(this);
            bankMenu.add(b);
            jBar.add(bankMenu);
            setJMenuBar(jBar);
            // Title JBankset
            title = new JLabel(MAIN_TITLE_TEXT);
            contentPane.add(title);
        public void actionPerformed(ActionEvent arg0)
            String command = arg0.getActionCommand();
            if (command.equals(BANK_MENUITEM))
                title.setText(MAIN_TITLE_TEXT + " " +
                        BANK_MENUITEM);
            else if (command.equals(NEW_ACCT_MENUITEM))
                title.setText(MAIN_TITLE_TEXT + " " +
                        NEW_ACCT_MENUITEM);
                newAccountFrame();
            else if (command.equals(OPEN_ACCT_MENUITEM))
                title.setText(MAIN_TITLE_TEXT + " " +
                        OPEN_ACCT_MENUITEM);
            else if (command.equals(DELETE_ACCT_MENUITEM))
                title.setText(MAIN_TITLE_TEXT + " " +
                        DELETE_ACCT_MENUITEM);
            else if (command.equals(TRANSFER_ACCT_MENUITEM))
                title.setText(MAIN_TITLE_TEXT + " " +
                        TRANSFER_ACCT_MENUITEM);
            else if (command.equals(OVERVIEW_ACCT_MENUITEM))
                title.setText(MAIN_TITLE_TEXT + " " +
                        OVERVIEW_ACCT_MENUITEM);
            else if (command.equals(LOGIN_BUTTON))
                Scanner loginFile = null;
                String currentFileLoginName;
                String triedLogin = loginField.getText();
                try
                   loginFile = new Scanner(new FileInputStream("logins.txt"));
                catch(FileNotFoundException e)
                    System.out.println("Internal Error");
                    System.exit(0);
                do
                   currentFileLoginName = loginFile.nextLine();
                   if  (processLogin(currentFileLoginName, triedLogin, loginFile)) //Send Logins&File | Return boolean
                       loginFile.close(); //Close File
                       break; //Login true. Break out of while loop
                while (loginFile.hasNextLine() == true);
            else if (command.equals(REGISTER_BUTTON))
                registrationFrame();
            else if (command.equals(NEW_USER_REGISTER_BUTTON))
                registrationFrame.setVisible(false);
                if (checkFields() == false)
                    registrationFrame.dispose();
                    registrationFrame();
                else
                registerNewUser();
            else if (command.equals(CHECKING_RADIO_BUTTON))
                savingsSelected = false;
                checkingSelected = true;
                retirementSelected = false;
            else if (command.equals(SAVINGS_RADIO_BUTTON))
                savingsSelected = true;
                checkingSelected = false;
                retirementSelected = false;
            else if(command.equals(RETIREMENT_RADIO_BUTTON))
                savingsSelected = false;
                checkingSelected = false;
                retirementSelected = true;
            else if (command.equals(NEW_ACCT_OK_BUTTON))
                double doubleInitialMoney = Double.parseDouble(initialMoneyField.getText());
                if (savingsSelected)
                    currentUserAccount.registerAccount("savings");
                    currentUserAccount.deposit("savings", doubleInitialMoney);
                if (checkingSelected)
                    currentUserAccount.registerAccount("checking");
                    currentUserAccount.deposit("checking", doubleInitialMoney);
                if (retirementSelected)
                    currentUserAccount.registerAccount("register");
                    currentUserAccount.deposit("retirement", doubleInitialMoney);
                newAccountFrame.dispose();
        private void loginFrame()
            loginFrame.setTitle("JBank -- Login Required");
            loginFrame.setDefaultLookAndFeelDecorated(true);
            loginFrame.setBounds(400,350,225,130);
            JTextField login = new JTextField("User ID");
            JTextField password = new JTextField("Password");
            loginFrame.setLayout(new GridLayout(0,2));
            //Button Panel
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new GridLayout(4,0));
            JLabel space = new JLabel("                   ");
            JButton okButton = new JButton("Login");
            okButton.isDefaultButton();
            okButton.setVerticalTextPosition(AbstractButton.CENTER);
            JButton register = new JButton("Register");
            register.setVerticalTextPosition(AbstractButton.CENTER);
            okButton.setActionCommand(LOGIN_BUTTON);
            register.setActionCommand(REGISTER_BUTTON);
            okButton.addActionListener(this);
            register.addActionListener(this);
            buttonPanel.add(okButton);
            buttonPanel.add(space);
            buttonPanel.add(register);
            buttonPanel.add(space);
            //Text Panel
            JPanel textPanel = new JPanel();
            textPanel.setLayout(new GridLayout(4,0));
            JLabel userIDLabel = new JLabel("User ID:");
            JLabel passwordLabel = new JLabel("Password:");
            loginField = new JTextField(14);
            passwordField = new JPasswordField(14);
            textPanel.add(userIDLabel);
            textPanel.add(loginField);
            textPanel.add(passwordLabel);
            textPanel.add(passwordField);
            loginFrame.add(textPanel);
            loginFrame.add(buttonPanel);
            loginFrame.setVisible(true);
        private void registrationFrame()
            loginFrame.setVisible(false);
            //Registration's Frame
            registrationFrame.setTitle("JBank -- Registration");
            registrationFrame.setDefaultLookAndFeelDecorated(true);
            registrationFrame.setBounds(400,350,300,300);
            registrationFrame.setLayout(new BorderLayout());
            //Buttons
            JButton registerButton = new JButton("Register");
            JButton cancelButton = new JButton("Cancel");
            //Text Fields
            regNameField = new JTextField(20);
            regSSNField = new JTextField(8);
            regUserField = new JTextField(14);
            regPasswordField = new JPasswordField(14);
            //Labels
            JLabel nameLabel = new JLabel("Name:  ");
            JLabel ssnLabel = new JLabel("Social Security: ");
            JLabel newUserLabel = new JLabel("Desired User ID: ");
            JLabel newPasswordLabel = new JLabel("Desired Password: ");
            //Top Panel
            JPanel newUserFieldsPanel = new JPanel();
            newUserFieldsPanel.setLayout(new GridLayout(8,0));
            //Bottom Panel
            JPanel newUserButtonsPanel = new JPanel();
            newUserButtonsPanel.setLayout(new GridLayout(0,2));
            //Add
            newUserFieldsPanel.add(nameLabel);
            newUserFieldsPanel.add(regNameField);
            newUserFieldsPanel.add(ssnLabel);
            newUserFieldsPanel.add(regSSNField);
            newUserFieldsPanel.add(newUserLabel);
            newUserFieldsPanel.add(regUserField);
            newUserFieldsPanel.add(newPasswordLabel);
            newUserFieldsPanel.add(regPasswordField);
            newUserButtonsPanel.add(registerButton);
            newUserButtonsPanel.add(cancelButton);
            registrationFrame.add(newUserFieldsPanel, BorderLayout.CENTER);
            registrationFrame.add(newUserButtonsPanel, BorderLayout.SOUTH);
            //Action Listeners
            registerButton.setActionCommand(NEW_USER_REGISTER_BUTTON);
            cancelButton.setActionCommand(CANCEL_BUTTON);
            registerButton.addActionListener(this);
            cancelButton.addActionListener(this);
            registrationFrame.setVisible(true);
        private void newAccountFrame()
            //New Account Frame
            newAccountFrame.setTitle("Create New Account");
            newAccountFrame.setDefaultLookAndFeelDecorated(true);
            newAccountFrame.setBounds(400,350,300,300);
            newAccountFrame.setLayout(new BorderLayout());
            //Buttons
            JButton newAcctOkButton = new JButton("OK");
            JButton newAcctCancelButton = new JButton("Cancel");
            //Radio Buttons
            JRadioButton checkingOption = new JRadioButton("Checking Account");
            JRadioButton savingsOption = new JRadioButton("Savings Account");
            JRadioButton retirementOption = new JRadioButton("Retirement Account");
            //Group 'em
            ButtonGroup accountSettings = new ButtonGroup();
            accountSettings.add(checkingOption);
            accountSettings.add(savingsOption);
            accountSettings.add(retirementOption);
            //Text Fields
            initialMoneyField = new JTextField("0", 8);
            //Labels
            JLabel depositLabel = new JLabel("Initial Deposit:  ");
            JLabel optionLabel = new JLabel("What kind of account would \n"
            + "you like to create?");
            //Top Panel
            JPanel newAcctOptionsPanel = new JPanel();
            newAcctOptionsPanel.setLayout(new GridLayout(4,0));
            //Bottom Panel
            JPanel newAcctTextPanel = new JPanel();
            newAcctTextPanel.setLayout(new GridLayout(2,2));
            //Add
            newAcctOptionsPanel.add(optionLabel);
            newAcctOptionsPanel.add(checkingOption);
            newAcctOptionsPanel.add(savingsOption);
            newAcctOptionsPanel.add(retirementOption);
            newAcctTextPanel.add(depositLabel);
            newAcctTextPanel.add(initialMoneyField);
            newAcctTextPanel.add(newAcctOkButton);
            newAcctTextPanel.add(newAcctCancelButton);
            newAccountFrame.add(newAcctOptionsPanel, BorderLayout.CENTER);
            newAccountFrame.add(newAcctTextPanel, BorderLayout.SOUTH);
            //Action Listeners
            checkingOption.setActionCommand(CHECKING_RADIO_BUTTON);
            savingsOption.setActionCommand(SAVINGS_RADIO_BUTTON);
            retirementOption.setActionCommand(RETIREMENT_RADIO_BUTTON);
            checkingOption.addActionListener(this);
            savingsOption.addActionListener(this);
            retirementOption.addActionListener(this);
            newAcctOkButton.setActionCommand(NEW_ACCT_OK_BUTTON);
            newAcctCancelButton.setActionCommand(NEW_ACCT_CANCEL_BUTTON);
            newAcctOkButton.addActionListener(this);
            newAcctCancelButton.addActionListener(this);
            newAccountFrame.setVisible(true);
        private boolean checkFields()
            //Check Name Field
            String triedName = regNameField.getText();
            if (triedName.length() == 0)
                JOptionPane.showMessageDialog(null,
                "Empty Name Field. Try Again.",
                "Error Message",
                JOptionPane.ERROR_MESSAGE);
                return false;
            //Check SSN
            String triedSS = regSSNField.getText();
            int parsedSS = 0;
            try
                parsedSS = Integer.parseInt(triedSS);
            catch(Exception e)
                JOptionPane.showMessageDialog(null,
                "Numbers only in Social Security Field!\n Try Again.",
                "Error Message",
                JOptionPane.ERROR_MESSAGE);
                return false;
            if (triedSS.length() < 8)
                JOptionPane.showMessageDialog(null,
                "Social Security Number is not 8 Digits.\n Try Again.",
                "Error Message",
                JOptionPane.ERROR_MESSAGE);
                return false;
            //Check User ID
            String triedUser = regUserField.getText();
            if (triedUser.length() < 6)
                JOptionPane.showMessageDialog(null,
                "Desired User ID too short.\n Try Again",
                "Error Message",
                JOptionPane.ERROR_MESSAGE);
                return false;
            //Check Password
            char[] triedPassword = regPasswordField.getPassword();
            String stringPassword = triedPassword.toString();
            if (stringPassword.length() < 6)
                JOptionPane.showMessageDialog(null,
                "Desired Password Too Short. \n Try Again.",
                "Error Message",
                JOptionPane.ERROR_MESSAGE);
                return false;
            return true;
        private boolean registerNewUser()
            FileOutputStream writer;
            try
                BufferedWriter out = new BufferedWriter(new FileWriter("logins"));
                out.write(regUserField.getText());
                char [] tempPass = regPasswordField.getPassword();
                String tempString = tempPass.toString();
                out.write("\n" + tempString);
                out.close();
            catch(IOException e)
                System.out.println("Writing file error.");
                System.exit(0);
            int intSS = Integer.parseInt(regSSNField.getText());
            currentUserAccount = new Account(regNameField.getText(), intSS);
            return true;
        private boolean processLogin(String currentFileLoginName, String triedLogin, Scanner loginFile)
            char[] userPassword = passwordField.getPassword();
            if (currentFileLoginName.equals(triedLogin))
                String currentFilePassword = loginFile.nextLine(); //Login recognized, go to next line for password
                char[] charPassword = currentFilePassword.toCharArray();
                if (charPassword.length == userPassword.length) //Password Lengths match?
                    if(Arrays.equals(userPassword, charPassword)) //Do characters match?
                        trueUser = true;
                        loginFrame.dispose();
                        return true;
                else
                    JOptionPane.showMessageDialog(null, //Notify User of Incorrect password
                     "Invalid password. Try again.",
                     "Error Message",
                     JOptionPane.ERROR_MESSAGE);
                     return false;
            else
                JOptionPane.showMessageDialog(null, //Notify user of unrecognized login
                "Unknown User ID. Try again\n or Register.",
                "Error Message",
                JOptionPane.ERROR_MESSAGE);
                return false;
            return false;
        private class Account
        private String name;
        private int ssn;
        private double totalUserMoney;
        private boolean checking = false;
        private boolean savings = false;
        private boolean retirement = false;
        private double checking_holdings;
        private double savings_holdings;
        private double retirement_holdings;
       public Account(String userName, int ss)
           name = userName;
           ssn = ss;
        public int getSSN()
            return ssn;
        public double getTotalUserMoney()
            return totalUserMoney;
        public boolean getUserAccounts(String type)
           if (type.equals("checking"))
               if (checking == false)
               return false;
               else
               return true;
            if (type.equals("savings"))
                if (savings == false)
                return false;
                else
                return true;
            if (type.equals("retirement"))
                if (retirement == false)
                return false;
                else
                return true;
            return false;
        public void registerAccount(String type)
            if (type.equals("checking"))
            checking = true;
            else if (type.equals("savings"))
            savings = true;
            else if (type.equals("retirement"))
            retirement = true;
            else
            System.out.println("Internal error"); //Should not reach here
        public boolean withdraw(String type, Double moneyAmount)
            if(getUserAccounts(type))
                if(type.equals("checking"))
                    if (moneyAmount > checking_holdings)
                        JOptionPane.showMessageDialog(null,"Insufficient holdings in checking account");
                    else
                        checking_holdings -= moneyAmount;
                        totalUserMoney -= moneyAmount;
                        return true;
                if(type.equals("savings"))
                    if (moneyAmount > checking_holdings)
                        JOptionPane.showMessageDialog(null,"Insufficient holdings in savings account");
                    else
                        savings_holdings -= moneyAmount;
                        totalUserMoney -= moneyAmount;
                        return true;
                if(type.equals("retirement"))
                    if (moneyAmount > checking_holdings)
                        JOptionPane.showMessageDialog(null,"Insufficient holdings in retirement account");
                    else
                        retirement_holdings -= moneyAmount;
                        totalUserMoney -= moneyAmount;
                        return true;
            else
                JOptionPane.showMessageDialog(null,"No such account exists");
                return false;
        public boolean deposit(String type, Double moneyAmount)
            if(getUserAccounts(type))
                if(type.equals("checking"))
                    checking_holdings += moneyAmount;
                    totalUserMoney += moneyAmount;
                    return true;
                if(type.equals("savings"))
                    savings_holdings += moneyAmount;
                    totalUserMoney += moneyAmount;
                    return true;
                if(type.equals("retirement"))
                    retirement_holdings += moneyAmount;
                    totalUserMoney += moneyAmount;
                    return true;
            else
                JOptionPane.showMessageDialog(null,"No such account exists");
                return false;
        public void deleteAccount(String type)
            if (type.equals("checking"))
                totalUserMoney -= checking_holdings;
                checking = false;
            if (type.equals("savings"))
                totalUserMoney -= savings_holdings;
                savings = false;
            if (type.equals("retirement"))
                totalUserMoney -= retirement_holdings;
                retirement = false;
        public void showAccountInfo()
            if (checking == true && savings == true && retirement == true)
            System.out.println(name + "'s Accounts: " + "\nChecking Account: $" + checking_holdings
            + "\nSavings Account: $" + savings_holdings + "\nRetirement Account: $" +
            retirement_holdings + "\n\nTotal: $" + totalUserMoney);
        public void showAccountInfo(String type)
            System.out.println(name + " ");
    }

    In the future, do not post eleventeenkathousand lines of code. No one is going to read it all and - quite frankly - no one really cares.
    As for the issue at hand, whenever you are going to access the file system, a remote server, access the clipboard and a handful of other "security" related issues, you must sign your applet.
    Google for sun's tutorial on signing applets.

  • Can you write this program more efficiently?

    Hello :)
    I am trying to write a program that does the following:
    "The prime factors of 13195 are 5, 7, 13 and 29.
    What is the largest prime factor of the number 317584931803?"
    Since we are dealing with such a huge number, I've used the BigInteger class to handle it. But the problem is, the following code is inefficient..... I mean, its been calculating for the past 2.5 hours ;( I its still only on the 8th digit. I was wondering if someone could write this more efficiently?
    import java.math.*;
    public class euler6 {
         public static void main (String arhs[]){
               BigInteger a[]=new BigInteger[999];
               int j=0;
               BigInteger bi = new BigInteger("317584931803"); //*********
               BigInteger i=new BigInteger("2");
               final BigInteger one=new BigInteger("1");     
               final BigInteger zero=new BigInteger("0");     
               boolean state     ;
         for(;i.compareTo(bi)==-1;i=i.add(one))
              { //System.out.println(i);
                //System.out.println(bi.mod(i)+"*");
                //System.out.println(bi.mod(i).equals(zero)+"**");
                   if ((bi.mod(i).equals(zero))&& (findPrime(i)))
                        {a[j]=i;
                         j++;}
         for(int f=0;f<a.length;f++)
              System.out.print(a[f]+" ");
         public static boolean findPrime(BigInteger n){
                   final BigInteger one=new BigInteger("1");
                   final BigInteger zero=new BigInteger("0");
                   BigInteger x=new BigInteger("2");
                   for(;n.divide(x).compareTo(one)==1;x=x.add(one))
                        if (n.mod(x).equals(zero))          
                             return false;
                        return true;

    Hi,
    I agree with prev poster, you don't have to use BigInteger since long is sufficient.
    Try this, more optimized than initial version, yet still using brute force ... The drawback is, if the given number 317584931803 is a prime number .. then ... it will also take 24 hours to compute ... can't help that.
    My idea is, let's say I have number 30.
    So, I will search all possibility between 2 to 15. My reason is the factor will not exceed from 30 div 2 which is 15.
    While doing brute, I will decrease the iteration boundary.
    Eg:
    - 30 is succesfully devided by 2, then iteration will stop bruting force up to iteration #15.
    - next iteration, 30 is succesfully devided by 3, then iteration will stop bruting force up to iteration #10.
    - next iteration, 30 is succesfully devided by 5, then iteration will stop bruting force up to iteration #6.
    So, total there is only 4 iterations to check the factor of 30. And I get these number: 2, 15, 3, 10, 5, 6
    The next step would be checking which of the numbers are prime, and we get 2, 3, and 5.
    My algorithm is something like this:
    import java.util.*;
    public class PF // stands from Prime Factors ..
    public static void main(String s[]) throws Exception {
            long num = 317584931803l;
            List factors = new ArrayList(255);
            long div2 = (long) (num / 2);
            for (int i=2; i<=div2; i++) {
                    if (num % i == 0) {
                            div2 = (int) (num / i);
                            factors.add(new Long(i));
                            factors.add(new Long(div2));
                    Thread.yield();
            Iterator iter = factors.iterator();
            while (iter.hasNext()) {
                    long factor =  ((Long) iter.next()).longValue();
                    if (isPrime(factor)) {
                            System.out.println(factor);
    static boolean isPrime(long num) throws Exception {
            long div2 = (long) (num / 2);
            for (int i=2; i<div2; i++)  {
                    if (num % i == 0) return false;
                    Thread.yield();
            return true;
    }The reason I put Thread.yield() is so it won't hang your machine ... this happens if the big number you test is a prime number...
    My machine (Intel pentium III 700 MHz, 512 MB SDRAM) takes less than 1 second to compute ... ;-)
    Alex

Maybe you are looking for

  • Simple Q. how to store/publish acrobat form and "return" as email attachment

    New to acrobat.com and wondering if this can be done (with acrobat.com). I have roughly 20 acrobat forms that I want to be accessible on the internet for about 5 specific people to access via the internet. The goal would be for them to click on the a

  • Call procedure that uses REF CURSOR?

    Can someone tell me how to call a procedure that uses a REF CURSOR? Procedure is something like this: PROCEDURE my_proc P_PROG_ID IN VARCHAR2, P_CRITERIA IN VARCHAR2, P_TASKCURSOR OUT MYREFCUR IS blah, blah blah I tried this to call the procedure: ex

  • Reg reconcilation account for customers

    Hi,         when i create vendor , there is reconcilation account which is link to G/L, but when i am creating customer, i am not finding any field to enter reconcilation account, i am not able to link customer account to G/L acccount,               

  • T500 - poor display quality

    I have T500 with WXGA TFT LED Backlight and integrated Intel graphics and I'm very disappointed with it. This LCD presents very poor quality in terms of viewing angles (not only vertical but also horizontal), colors (they are somehow washed-out, not

  • Reverse engineering with Rational Rose

    Is anybody using the above? If so, have you developed any scripts to facilitate updating the Rose model, and which you'd be willing to share? Or perhaps discuss jointly writing same? Ideally, there would be an Fscript to facilitate exposting Forte pr