Int to Integer

how to convert int value to Integer value?
Thanks.

running the risk of sounding stupid
what's the difference?Sir,
An int is a primitive. An Integer is an object. Specifically a wrapper object for the primitive type int.
Java has both objects and primitives.
Sincerely,
Slappy

Similar Messages

  • Converting int[] to Integer[]

    How to convert an int array to Integer[] without iterating the int[]?
    we can traverse the int[] and add to Integer[]. But the traversing takes too much time. Is there any method to do the above conversion?

    If you are using 1.5, you can use the individual elements of the int[] as if they were an Integer, so why do you need to convert it? If it is to pass the array as an argument, then sorry, you are going to have to traverse the arrays and set the elements. And, at most, this will take a second or two of time (even if you have an array of nearly max size), so in what way is this "taking too much time"?
    Edit: And any API method to do this with a single line of code, would still, inside the method, need to traverse the arrays, so now time would be saved. If it is to save programming time, then take a few minutes to write a method for it now, and then every time you need it in the future, just use that method.

  • Int or Integer

    Having a problem with my entity bean.......... I have set my primary key type to type java.lang.Integer.... my ejbCreate is returning an Integer but when i try to compile is says that type int is required. i cannot change it to an int as the primary key has to be an object and it will not deploy. Why is it asking for an int? what is asking the the ejbCreate for an int? any help!

    Hi,
    If you are doing an insert within your create you should have something like this...
    pstmt.setInt(1,ID.intValue() );Where pstmt is the PreparedStatement for the insert! Send ur code so I can understand what your trying to do.
    Hope it helps

  • String.valueOf(int i)  /   Integer.toString()

    What's the difference between these methods? They seem to both do the same thing... convert an int into a string

    No, they don't
    static String valueOf(int i)
              Returns the string representation of the int argument.
    String toString()
              Returns a String object representing this Integer's value. Perhaps you intended to compare the String.valueOf to this?
    static String toString(int i)
              Returns a String object representing the specified integer. If so, then yes, they do the same thing.

  • Int and Integer

    whats the difference between these two anyway..?

    int is a primitive type and Integer is a class. You would generally use primitive types wherever possible because they are much more efficient. You would use classes, for instance, if you have to put your values into a collection such as an ArrayList.

  • Fundamental Question about int vs Integer

    I don't really understand what the difference is between using the "int" keyword and using the Integer type. I've come to realise that "int" cannot be null whereas Integer can be null but why isn't int just an Integer type? Like an alias of sorts. I realise this a fairly basic question but I'm sure I'm not the only one pondering this :)

    I'm not sure if the autoboxing stuff in 1.5 affects
    this at all or not, but one key difference between
    objects and primitives is that primitives get passed
    by value, whereas objects are passed by reference.
    NOOOOOOOOOOOOOO!
    Wrong. Wrong. Wrong. Wrong. Wrong.
    Everything in Java is passed "by value". Everything.
    Pass-by-value
    - When an argument is passed to a function, the invoked function gets a copy of the original value.
    - The local variable inside the method declaration is not connected to the caller's argument; any changes made to the values of the local variables inside the body of the method will have no effect on the values of the arguments in the method call.
    - If the copied value in the local variable happens to be a reference (or "pointer") to an object, the variable can be used to modify the object to which the reference points.
    Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory.... The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.
    -- James Gosling, et al., The Java Programming Language, 4th Edition

  • Conversion int to Integer

    I want to retrieve the data of a ResultSet by rs.getInt(3), but I need to convert this data to an Integer, because my PrimaryKey is in Integer format. How could I retrieve an Integer?

    Integer MyInteger = new Integer(rs.getInt(3));
    I want to retrieve the data of a ResultSet by
    rs.getInt(3), but I need to convert this data to an
    Integer, because my PrimaryKey is in Integer format.
    How could I retrieve an Integer?

  • Unsigned int to integer conversion

    Hi,
    I have an unsigned integer column in my database table. If I try to retreive the value of the column using resultset.getInt() I'm getting "Numeric value overflow" error as it exceeds the INT_MAX value.
    For eg., if the column value : 4294967295, the expected value from resultset.getInt() is -1 or Numeric Value Overflow error ?
    Is it valid to retrieve the value using getInt() or should I use getLong()?.
    Kindly Clarify.
    Thanks,
    Radhika.

    use getLong

  • How to convert an Integer to int

    Integer y = new Integer(1);
    int x = ????(y);
    What is the missing command to do the above conversion ?
    I've tried casting etc.
    It's mid nite and I'm still at work!
    Appreciate all help. Thanks!

    Integer is an Object. int is a primitive base type. to convert an Integer Object into an int:
    //let's say you read a line from a file, and the line is this
    5
    //normally, since files contain characters, you would call a method that reads in String Objects
    //so the 5 is actually a String, which you need to convert to an int to use for math, calculations,
    //expressions, etc.
    String blah = Keyboard.readLine();
    int x = Integer.parseInt(blah);
    // now x equals the int 5.
    hope this helps.

  • Converting Integer to int - Junit

    Hello
    I have a problem with a Junit test case. The search function did not return any helpful results, so I'm trying my luck here.
    I'm using Junit 4.4 and JDK1.6.0_01
    My class which I would like to test looks like this:
    public class SortedIntArrayList<Integer> extends ArrayList<Integer> {
         public SortedIntArrayList(){
              super();
        /* adds an integer val such that the list is
           always sorted in ascending order
         public void addInt(Integer val){
         // @TODO implementation will follow
    }and this is my test class
    public class SortedIntArrayListTest extends TestCase {
         private SortedIntArrayList<Integer> saExp = new SortedIntArrayList<Integer>();
         private SortedIntArrayList<Integer> saAct = new SortedIntArrayList<Integer>();
         @Override
            public void setUp(){
              // set up the actual sortedIntArrayList
              saAct.add(-6);
              saAct.add(2);
              saAct.add(9);
              saAct.add(22);
              saAct.add(69);
              // set up the expected sortedIntArrayList
              saExp.add(-6);
              saExp.add(2);
              saExp.add(9);
              saExp.add(22);
              saExp.add(69);
         // add an element at the beginning of the arraylist
         public void testAddIntFirstElement(){
              int val = -10;
              this.saAct.add(0,val);
              this.saExp.addInt(new Integer(val));
              assertEquals(saAct,saExp);
    }Now to my problem.
    I'm trying to create a method addInt(Integer) in my SortedIntArrayList class, such that the resulting arrayList will be ordered.
    In my addInt(Integer val) method I want to get the int value from the val Integer object to compare it to the values already in the arrayList.
    What I tried to do:
    public void addInt(Integer val){
         if(this.get(0).intValue()<val.intValue()){
             // do something
    }Does not work! Also, Integer.parseInt and all these Integer methods do not show up.
    When I open a new project and try something like
    public static void main(String[] args) {
       int i;
       Integer itgr = new Integer(10);
       i = itgr.intValue();
    }it does work.
    What am I doing wrong? By the way, I tried it in Eclipse as well as in NetBeans.
    Thanks for your help
    Greetings, David
    Edit: Well, after some research I found out that my actual problem is that I cannot Instantiate Integer in my extended class like:
    Integer i = new Integer(30);
    message: cannot instantiate integer.
    Any ideas why that is?
    Edited by: strad on Nov 9, 2007 8:43 AM

    It sounds like you've defined a class and named it .... Integer! So the compiler thinks "Integer" is your class and not java.lang.Integer.
    Solution: rename or get rid of your Integer class, or be forced to write this everywhere:
    java.lang.Integer x = new java.lang.Integer(42);

  • How to switch a decimal integer to a hexadecimal int?

    How to switch a decimal integer to a hexadecimal int? And contrary too?

    If you are talking about String representations of integers, you can use the methods in java.lang.Integer:
    For example, to convert from hexadecimal notation to an int-value you can use:
    int x = Integer.parseInt("FF00E", 16);  // Radix 16To convert an int value to to hexadecimal notation use:
    String x = Integer.toHexString(1778);S&oslash;ren

  • The length of an integer

    Hello.
    Just for couriosity I'd like to calculate the length of an int and by that I mean return the number of digits.
    I know how to do this 'manually', but is there a method somewhere that looks a bit like this:
    object.calcInt(47653);//returns 5Thanks in advance

    Interesting. Nobody likes the log method even though it is 30% faster.
    public class Garbage
        public static final int FIRST_INT = Integer.MAX_VALUE - 10000;
        public static final int LAST_INT  = Integer.MAX_VALUE;
        public static final int TESTS = 1000;
        public static void main(String args[])
            long divideTestTime = 0;
            long stringTestTime = 0;
            long logTestTime = 0;
            DivideTest divideTest = new DivideTest();
            StringTest stringTest = new StringTest();
            LogTest logTest = new LogTest();
            for (int i = 0; i < TESTS; i++)
                    divideTestTime += runTest(divideTest);
                    stringTestTime += runTest(stringTest);
                    logTestTime += runTest(logTest);
            System.out.println("Divide-test Time: " + divideTestTime);
            System.out.println("String-test Time: " + stringTestTime);
            System.out.println("Log-test Time: " + logTestTime);
        public static long runTest(Test test)
            long start = System.currentTimeMillis();
            for (int i = FIRST_INT; i < LAST_INT; i++)
                    test.lengthOf(i);
            return System.currentTimeMillis() - start;
    interface Test {
        public int lengthOf(int i);
    class DivideTest implements Test {
        public int lengthOf(int i) {
            int size = 0;
            do {
                size++;
                i /= 10;
            } while(i > 0);
            return size;
    class StringTest implements Test {
        public int lengthOf(int i) {
            return String.valueOf(i).length();
    class LogTest implements Test
        private static final double l210 = Math.log(10);
        public int lengthOf(int i) {
            return (int)(1 + (Math.log(0.5 + i) / l210));
    }

  • Class & int/String issues

    Upon compiling, I am receiving the following errors:
    TeamRosterApp.java:153: cannot find symbol
    symbol : class ButtonPanel
    location: class TeamRosterPanel
    ButtonPanel buttonPanel;
    ^
    TeamRosterApp.java:166: cannot find symbol
    symbol : class ButtonPanel
    location: class TeamRosterPanel
    buttonPanel = new ButtonPanel();
    ^
    2 errors
    I've included the code below, but I having difficulty understanding why it cannot find the ButtonPanel class when that class is specified in the code (Line 364).
    Thanks in advance for your help!
    //Modified by Doe, John 20OCT2007
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.JTextComponent;
    import java.util.ArrayList;
    import java.text.*;
    import java.lang.*;
    import java.util.*;
    public class TeamRosterApp
         public static void main(String[] args)
              TeamIO.getTeam();
                    JFrame frame = new TeamRosterFrame();
                    frame.setVisible(true);
    class Player
         String lname;
         String fname;
         int number;
         public Player()
              lname = "";
              fname = "";
              number = 0;
         public Player(String lname, String fname, int number)
              this.lname = lname;
              this.fname = fname;
              this.number = number;
         public void setLastName(String lname)
              this.lname = lname;
         public String getLastName()
              return lname;
         public void setFirstName(String fname)
              this.fname = fname;
         public String getFirstName()
              return fname;
         public void setNumber(int number)
              this.number = number;
         public int getNumber()
              return number;
    class TeamIO
         private static final ArrayList<Player> team = new ArrayList<Player>();
         public static ArrayList<Player> getTeam()
              team.add(new Player("Doe", "John", 69));
              team.add(new Player("Berg", "Laura", 44));
              team.add(new Player("Bustos", "Crystl", 6));
              team.add(new Player("Clark", "Jamie", 24));
              team.add(new Player("Fernandez", "Lisa", 16));
              team.add(new Player("Finch", "Jennie", 27));
              team.add(new Player("Flowers", "Tairia", 11));
              team.add(new Player("Freed", "Amanda", 7));
              team.add(new Player("Giordano", "Nicole", 4));
              team.add(new Player("Harrigan", "Lori", 21));
              team.add(new Player("Jung", "Lovieanne", 3));
              team.add(new Player("Kretchman", "Kelly", 12));
              team.add(new Player("Lappin", "Lauren", 37));
              team.add(new Player("Mendoza", "Jessica", 2));
              team.add(new Player("O'Brien-Amico", "Lisa", 20));
              team.add(new Player("Nuveman", "Stacy", 33));
              team.add(new Player("Osterman", "Catherine", 8));
              team.add(new Player("Topping", "Jennie", 31));
              team.add(new Player("Watley", "Natasha", 29));
              System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              for(int i = 0; i < team.size(); i++)
                   Player p = (Player)team.get(i);
                   System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
                   System.out.println("****************************************");
              return new ArrayList<Player>(team);
         public static ArrayList<Player> saveTeam()
              System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              for(int i = 0; i < team.size(); i++)
              Player p = (Player)team.get(i);
              System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
              System.out.println("****************************************");
              return new ArrayList<Player>(team);
    class TeamRosterFrame extends JFrame
        public TeamRosterFrame()
            String me = "Campbell, Corey";
              String date;
              Date now = new Date();
              DateFormat longDate = DateFormat.getDateInstance(DateFormat.LONG);
              date = longDate.format(now);
              setTitle("Team Roster "+me+" "+date);
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(new TeamRosterPanel());
            this.pack();
            centerWindow(this);
        private void centerWindow(Window w)
            Toolkit tk = Toolkit.getDefaultToolkit();
            Dimension d = tk.getScreenSize();
            setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    class TeamRosterPanel extends JPanel
         ArrayList<Player>team;
         Player newPlayer = null;
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         public TeamRosterPanel()
              // fill the team ArrayList
              team = TeamIO.getTeam();
              // add the panels
              setLayout(new GridBagLayout());
              selectorPanel = new teamSelectorPanel();
              add(selectorPanel, getConstraints(0,0,1,1, GridBagConstraints.WEST));
              playerPanel = new PlayerDisplayPanel();
              add(playerPanel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
              buttonPanel = new ButtonPanel();
              add(buttonPanel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
              // set the initial player to be displayed
              playerPanel.showPlayer(team.get(0));
              selectorPanel.selectPlayer(team.get(0));
         // a method for setting grid bag constraints
         private GridBagConstraints getConstraints(int gridx, int gridy,
              int gridwidth, int gridheight, int anchor)
              GridBagConstraints c = new GridBagConstraints();
              c.insets = new Insets(5, 5, 5, 5);
              c.ipadx = 0;
              c.ipady = 0;
              c.gridx = gridx;
              c.gridy = gridy;
              c.gridwidth = gridwidth;
              c.gridheight = gridheight;
              c.anchor = anchor;
              return c;
         class teamSelectorPanel extends JPanel implements ActionListener
              public JComboBox    playerComboBox;
              private JLabel      playerLabel;
              boolean filling = false;            // used to indicate the combo box is being filled
              public teamSelectorPanel()
                   // set panel layout
                   setLayout(new FlowLayout(FlowLayout.LEFT));
                   // Player label
                   playerLabel = new JLabel("Select Player:");
                   add(playerLabel);
                   // Player combo box
                   playerComboBox = new JComboBox();
                   fillComboBox(team);
                   playerComboBox.addActionListener(this);
                   add(playerComboBox);
              public void actionPerformed(ActionEvent e)
                   if (!filling)
                        Player p = (Player)playerComboBox.getSelectedItem();
                        playerPanel.showPlayer(p);
              public void fillComboBox(ArrayList<Player> team)
              filling = true;
              playerComboBox.removeAllItems();
              for (Player p : team)
              playerComboBox.addItem(p);
              filling = false;
              public void selectPlayer(Player p)
                   playerComboBox.setSelectedItem(p);
              public Player getCurrentPlayer()
                   return (Player) playerComboBox.getSelectedItem();
         class PlayerDisplayPanel extends JPanel
              public JTextField   lastNameTextField,
                   firstNameTextField,
                   numberTextField;
              private JLabel      lastNameLabel,
                   firstNameLabel,
                   numberLabel;
              public PlayerDisplayPanel()
                   // set panel layout
                   setLayout(new GridBagLayout());
                   // last name label
                   lastNameLabel = new JLabel("Last name:");
                   add(lastNameLabel, getConstraints(0,0,1,1, GridBagConstraints.EAST));
                   // last name text field
                   lastNameTextField = new JTextField(10);
                   lastNameTextField.setEditable(false);
                   lastNameTextField.setFocusable(false);
                   lastNameTextField.addFocusListener(new AutoSelect());
                   add(lastNameTextField, getConstraints(1,0,1,1, GridBagConstraints.WEST));
                   // first name label
                   firstNameLabel = new JLabel("First name:");
                   add(firstNameLabel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
                   // first name text field
                   firstNameTextField = new JTextField(30);
                   firstNameTextField.setEditable(false);
                   firstNameTextField.setFocusable(false);
                   firstNameTextField.addFocusListener(new AutoSelect());
                   add(firstNameTextField, getConstraints(1,1,1,1, GridBagConstraints.WEST));
                   // number label
                   numberLabel = new JLabel("Number:");
                   add(numberLabel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
                   // number text field
                   numberTextField = new JTextField(10);
                   numberTextField.setEditable(false);
                   numberTextField.setFocusable(false);
                   numberTextField.addFocusListener(new AutoSelect());
                   numberTextField.addKeyListener(new IntFilter());
                   add(numberTextField, getConstraints(1,2,1,1, GridBagConstraints.WEST));
              public void showPlayer(Player p)
                   lastNameTextField.setText(p.getLastName());
                   firstNameTextField.setText(p.getFirstName());
                   numberTextField.setText(String.valueOf(p.getNumber()));
              public void clearFields()
                   lastNameTextField.setText("");
                   firstNameTextField.setText("");
                   numberTextField.setText("");
              // return a new Player object with the data in the text fields
              public Player getPlayer()
                   Player p = new Player();
                   p.setLastName(lastNameTextField.getText());
                   p.setFirstName(firstNameTextField.getText());
                   int n = Integer.parseInt(numberTextField.getText());
                   p.setNumber(n);
                   return p;
              public void setAddEditMode(boolean e)
                   lastNameTextField.setEditable(e);
                   lastNameTextField.setFocusable(e);
                   lastNameTextField.requestFocusInWindow();
                   firstNameTextField.setEditable(e);
                   firstNameTextField.setFocusable(e);
                   numberTextField.setEditable(e);
                   numberTextField.setFocusable(e);
              class AutoSelect implements FocusListener
                   public void focusGained(FocusEvent e)
                        if(e.getComponent() instanceof JTextField)
                             JTextField t = (JTextField) e.getComponent();
                             t.selectAll();
                   public void focusLost(FocusEvent e){}
              class IntFilter implements KeyListener
                   public void keyTyped(KeyEvent e)
                        char c = e.getKeyChar();
                        if ( c !='0' && c !='1' && c !='2' && c !='3' && c !='4' && c !='5'
                             && c !='6' && c !='7' && c !='8' && c !='9')
                             e.consume();
                   public void keyPressed(KeyEvent e){}
                   public void keyReleased(KeyEvent e){}
              class ButtonPanel extends JPanel
                   public JButton addButton,
                        editButton,
                        deleteButton,
                        acceptButton,
                        cancelButton,
                        exitButton;
                   public ButtonPanel()
                        // create maintenance button panel
                        JPanel maintPanel = new JPanel();
                        maintPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
                        // add button
                        addButton = new JButton("Add");
                        addButton.addActionListener(new AddListener());
                        maintPanel.add(addButton);
                        // edit button
                        editButton = new JButton("Edit");
                        editButton.addActionListener(new EditListener());
                        maintPanel.add(editButton);
                        // delete button
                        deleteButton = new JButton("Delete");
                        deleteButton.addActionListener(new DeleteListener());
                        maintPanel.add(deleteButton);
                        // accept button
                        acceptButton = new JButton("Accept");
                        acceptButton.setEnabled(false);
                        acceptButton.addActionListener(new AcceptListener());
                        maintPanel.add(acceptButton);
                        // cancel button
                        cancelButton = new JButton("Cancel");
                        cancelButton.setEnabled(false);
                        cancelButton.addActionListener(new CancelListener());
                        maintPanel.add(cancelButton);
                        // create exit button panel
                        JPanel exitPanel = new JPanel();
                        exitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
                        // exit button
                        exitButton = new JButton("Exit");
                        exitButton.addActionListener(new ExitListener());
                        exitPanel.add(exitButton);
                        // add panels to the ButtonPanel
                        setLayout(new BorderLayout());
                        add(maintPanel, BorderLayout.CENTER);
                        add(exitPanel, BorderLayout.SOUTH);
                   public void setAddEditMode(boolean e)
                        addButton.setEnabled(!e);
                        editButton.setEnabled(!e);
                        deleteButton.setEnabled(!e);
                        acceptButton.setEnabled(e);
                        cancelButton.setEnabled(e);
              class AddListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        newPlayer = new Player();
                        playerPanel.clearFields();
                        buttonPanel.setAddEditMode(true);
                        playerPanel.setAddEditMode(true);
              class EditListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        buttonPanel.setAddEditMode(true);
                        playerPanel.setAddEditMode(true);
              class DeleteListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        Player p = selectorPanel.getCurrentPlayer();
                        team.remove(p);
                        TeamIO.saveTeam();
                        selectorPanel.fillComboBox(team);
                        selectorPanel.selectPlayer(team.get(0));
                        playerPanel.showPlayer(team.get(0));
                        selectorPanel.playerComboBox.requestFocusInWindow();
              class AcceptListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        if (isValidData())
                             if (newPlayer != null)
                                  newPlayer = playerPanel.getPlayer();
                                  team.add(newPlayer);
                                  TeamIO.saveTeam();
                                  selectorPanel.fillComboBox(team);
                                  selectorPanel.selectPlayer(newPlayer);
                                  newPlayer = null;
                             else
                                  Player p = selectorPanel.getCurrentPlayer();
                                  Player newPlayer = playerPanel.getPlayer();
                                  p.setLastName(newPlayer.getLastName());
                                  p.setFirstName(newPlayer.getFirstName());
                                  p.setNumber(newPlayer.getNumber());
                                  TeamIO.saveTeam();
                                  selectorPanel.fillComboBox(team);
                                  selectorPanel.selectPlayer(p);
                                  playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
                             playerPanel.setAddEditMode(false);
                             buttonPanel.setAddEditMode(false);
                             selectorPanel.playerComboBox.requestFocusInWindow();
                   public boolean isValidData()
                        return SwingValidator.isPresent(playerPanel.lastNameTextField, "Last Name")
                             && SwingValidator.isPresent(playerPanel.firstNameTextField, "First Name")
                             && SwingValidator.isPresent(playerPanel.numberTextField, "Number")
                             && SwingValidator.isInteger(playerPanel.numberTextField, "Number");
              class CancelListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        if (newPlayer != null)
                             newPlayer = null;
                        playerPanel.setAddEditMode(false);
                        playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
                        buttonPanel.setAddEditMode(false);
                        selectorPanel.playerComboBox.requestFocusInWindow();
              class ExitListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        System.exit(0);
    }Swing Validator Code:
    //Programmed by Doe, John 20OCT2007
    import javax.swing.*;
    import javax.swing.text.JTextComponent;
    public class SwingValidator
         public static boolean isPresent(JTextComponent c, String title)
              if(c.getText().length()==0)
                   showMessage(c, title + " is a required field.\n" + "Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
              return true;
         public static boolean isInteger(JTextComponent c, String title)
              try
                   int i = Integer.parseInt(c.getText());
                   return true;
              catch(NumberFormatException e)
                   showMessage(c,title+" must be an integer.\n"+"Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
         private static void showMessage(JTextComponent c, String message)
              JOptionPane.showMessageDialog(c, message, "Invalid Entry", JOptionPane.ERROR_MESSAGE);
    }Edited by: kc0poc on Oct 21, 2007 8:17 AM

    Ok. Got it, understand it now. Corrected all 58 errors after created the top level classes. It compiles, but I'm now encountering a NullPointerException:
    Exception in thread "main" java.lang.NullPointerException
    at teamSelectorPanel.fillComboBox(TeamRosterAppTest.java:233)
    at teamSelectorPanel.<init>(TeamRosterAppTest.java:214)
    at TeamRosterPanel.<init>(TeamRosterAppTest.java:164)
    at TeamRosterFrame.<init>(TeamRosterAppTest.java:135)
    at TeamRosterAppTest.main(TeamRosterAppTest.java:17)
    I think I am not initializing something correctly and it involved the "team" variable. Thoughts anyone?
    Thank you as always!
    Below is my code:
    //Modified by Campbell, Corey 20OCT2007
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.JTextComponent;
    import java.util.ArrayList;
    import java.text.*;
    import java.lang.*;
    import java.util.*;
    public class TeamRosterAppTest
         public static void main(String[] args)
              TeamIO.getTeam();
              JFrame frame = new TeamRosterFrame();
              frame.setVisible(true);
    class Player
         String lname;
         String fname;
         int number;
         public Player()
              lname = "";
              fname = "";
              number = 0;
         public Player(String lname, String fname, int number)
              this.lname = lname;
              this.fname = fname;
              this.number = number;
         public void setLastName(String lname)
              this.lname = lname;
         public String getLastName()
              return lname;
         public void setFirstName(String fname)
              this.fname = fname;
         public String getFirstName()
              return fname;
         public void setNumber(int number)
              this.number = number;
         public int getNumber()
              return number;
    class TeamIO
         private static final ArrayList<Player> team = new ArrayList<Player>();
         public static ArrayList<Player> getTeam()
              team.add(new Player("Campbell", "Corey", 69));
              team.add(new Player("Berg", "Laura", 44));
              team.add(new Player("Bustos", "Crystl", 6));
              team.add(new Player("Clark", "Jamie", 24));
              team.add(new Player("Fernandez", "Lisa", 16));
              team.add(new Player("Finch", "Jennie", 27));
              team.add(new Player("Flowers", "Tairia", 11));
              team.add(new Player("Freed", "Amanda", 7));
              team.add(new Player("Giordano", "Nicole", 4));
              team.add(new Player("Harrigan", "Lori", 21));
              team.add(new Player("Jung", "Lovieanne", 3));
              team.add(new Player("Kretchman", "Kelly", 12));
              team.add(new Player("Lappin", "Lauren", 37));
              team.add(new Player("Mendoza", "Jessica", 2));
              team.add(new Player("O'Brien-Amico", "Lisa", 20));
              team.add(new Player("Nuveman", "Stacy", 33));
              team.add(new Player("Osterman", "Catherine", 8));
              team.add(new Player("Topping", "Jennie", 31));
              team.add(new Player("Watley", "Natasha", 29));
              //System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              //for(int i = 0; i < team.size(); i++)
              //          Player p = (Player)team.get(i);
              //          System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
              //System.out.println("****************************************");
              return new ArrayList<Player>(team);
         public static ArrayList<Player> saveTeam()
              System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              for(int i = 0; i < team.size(); i++)
                   Player p = (Player)team.get(i);
                   System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
              System.out.println("****************************************");
              return new ArrayList<Player>(team);
    class TeamRosterFrame extends JFrame
         public TeamRosterFrame()
              String me = "Campbell, Corey";
              String date;
              Date now = new Date();
              DateFormat longDate = DateFormat.getDateInstance(DateFormat.LONG);
              date = longDate.format(now);
              setTitle("Team Roster "+me+" "+date);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.add(new TeamRosterPanel());
              this.pack();
              centerWindow(this);
         private void centerWindow(Window w)
              Toolkit tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    class TeamRosterPanel extends JPanel
         ArrayList<Player>team;
         Player newPlayer = null;
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         public TeamRosterPanel()
              // fill the team ArrayList
              team = TeamIO.getTeam();
              // add the panels
              setLayout(new GridBagLayout());
              selectorPanel = new teamSelectorPanel();
              add(selectorPanel, getConstraints(0,0,1,1, GridBagConstraints.WEST));
              playerPanel = new PlayerDisplayPanel();
              add(playerPanel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
              buttonPanel = new ButtonPanel();
              add(buttonPanel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
              // set the initial player to be displayed
              playerPanel.showPlayer(team.get(0));
              selectorPanel.selectPlayer(team.get(0));
         // a method for setting grid bag constraints
         private GridBagConstraints getConstraints(int gridx, int gridy,
              int gridwidth, int gridheight, int anchor)
              GridBagConstraints c = new GridBagConstraints();
              c.insets = new Insets(5, 5, 5, 5);
              c.ipadx = 0;
              c.ipady = 0;
              c.gridx = gridx;
              c.gridy = gridy;
              c.gridwidth = gridwidth;
              c.gridheight = gridheight;
              c.anchor = anchor;
              return c;
    class teamSelectorPanel extends JPanel implements ActionListener
         public JComboBox playerComboBox;
         private JLabel playerLabel;
         boolean filling = false;            // used to indicate the combo box is being filled
         ArrayList<Player>team;
         PlayerDisplayPanel playerPanel;
         public teamSelectorPanel()
              // set panel layout
              setLayout(new FlowLayout(FlowLayout.LEFT));
              // Player label
              playerLabel = new JLabel("Select Player:");
              add(playerLabel);
              // Player combo box
              playerComboBox = new JComboBox();
              fillComboBox(team);
              playerComboBox.addActionListener(this);
              add(playerComboBox);
         public void actionPerformed(ActionEvent e)
              if (!filling)
                   Player p = (Player)playerComboBox.getSelectedItem();
                   playerPanel.showPlayer(p);
         public void fillComboBox(ArrayList<Player> team)
              filling = true;
              playerComboBox.removeAllItems();
              for (Player p : team)
              playerComboBox.addItem(p);
              filling = false;
         public void selectPlayer(Player p)
              playerComboBox.setSelectedItem(p);
         public Player getCurrentPlayer()
              return (Player) playerComboBox.getSelectedItem();
    class PlayerDisplayPanel extends JPanel
         public JTextField lastNameTextField,
              firstNameTextField,
              numberTextField;
         private JLabel lastNameLabel,
              firstNameLabel,
              numberLabel;
         public PlayerDisplayPanel()
              // set panel layout
              setLayout(new GridBagLayout());
              // last name label
              lastNameLabel = new JLabel("Last name:");
              add(lastNameLabel, getConstraints(0,0,1,1, GridBagConstraints.EAST));
              // last name text field
              lastNameTextField = new JTextField(10);
              lastNameTextField.setEditable(false);
              lastNameTextField.setFocusable(false);
              lastNameTextField.addFocusListener(new AutoSelect());
              add(lastNameTextField, getConstraints(1,0,1,1, GridBagConstraints.WEST));
              // first name label
              firstNameLabel = new JLabel("First name:");
              add(firstNameLabel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
              // first name text field
              firstNameTextField = new JTextField(30);
              firstNameTextField.setEditable(false);
              firstNameTextField.setFocusable(false);
              firstNameTextField.addFocusListener(new AutoSelect());
              add(firstNameTextField, getConstraints(1,1,1,1, GridBagConstraints.WEST));
              // number label
              numberLabel = new JLabel("Number:");
              add(numberLabel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
              // number text field
              numberTextField = new JTextField(10);
              numberTextField.setEditable(false);
              numberTextField.setFocusable(false);
              numberTextField.addFocusListener(new AutoSelect());
              numberTextField.addKeyListener(new IntFilter());
              add(numberTextField, getConstraints(1,2,1,1, GridBagConstraints.WEST));
         public void showPlayer(Player p)
              lastNameTextField.setText(p.getLastName());
              firstNameTextField.setText(p.getFirstName());
              numberTextField.setText(String.valueOf(p.getNumber()));
         public void clearFields()
              lastNameTextField.setText("");
              firstNameTextField.setText("");
              numberTextField.setText("");
         // return a new Player object with the data in the text fields
         public Player getPlayer()
              Player p = new Player();
              p.setLastName(lastNameTextField.getText());
              p.setFirstName(firstNameTextField.getText());
              int n = Integer.parseInt(numberTextField.getText());
              p.setNumber(n);
              return p;
         public void setAddEditMode(boolean e)
              lastNameTextField.setEditable(e);
              lastNameTextField.setFocusable(e);
              lastNameTextField.requestFocusInWindow();
              firstNameTextField.setEditable(e);
              firstNameTextField.setFocusable(e);
              numberTextField.setEditable(e);
              numberTextField.setFocusable(e);
         // a method for setting grid bag constraints
         private GridBagConstraints getConstraints(int gridx, int gridy,
              int gridwidth, int gridheight, int anchor)
              GridBagConstraints c = new GridBagConstraints();
              c.insets = new Insets(5, 5, 5, 5);
              c.ipadx = 0;
              c.ipady = 0;
              c.gridx = gridx;
              c.gridy = gridy;
              c.gridwidth = gridwidth;
              c.gridheight = gridheight;
              c.anchor = anchor;
              return c;
    class AutoSelect implements FocusListener
         public void focusGained(FocusEvent e)
              if(e.getComponent() instanceof JTextField)
                   JTextField t = (JTextField) e.getComponent();
                   t.selectAll();
         public void focusLost(FocusEvent e){}
    class IntFilter implements KeyListener
         public void keyTyped(KeyEvent e)
              char c = e.getKeyChar();
              if ( c !='0' && c !='1' && c !='2' && c !='3' && c !='4' && c !='5'
                   && c !='6' && c !='7' && c !='8' && c !='9')
                   e.consume();
         public void keyPressed(KeyEvent e){}
         public void keyReleased(KeyEvent e){}
    class ButtonPanel extends JPanel
         public JButton addButton,
              editButton,
              deleteButton,
              acceptButton,
              cancelButton,
              exitButton;
         public ButtonPanel()
              // create maintenance button panel
              JPanel maintPanel = new JPanel();
              maintPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
              // add button
              addButton = new JButton("Add");
              addButton.addActionListener(new AddListener());
              maintPanel.add(addButton);
              // edit button
              editButton = new JButton("Edit");
              editButton.addActionListener(new EditListener());
              maintPanel.add(editButton);
              // delete button
              deleteButton = new JButton("Delete");
              deleteButton.addActionListener(new DeleteListener());
              maintPanel.add(deleteButton);
              // accept button
              acceptButton = new JButton("Accept");
              acceptButton.setEnabled(false);
              acceptButton.addActionListener(new AcceptListener());
              maintPanel.add(acceptButton);
              // cancel button
              cancelButton = new JButton("Cancel");
              cancelButton.setEnabled(false);
              cancelButton.addActionListener(new CancelListener());
              maintPanel.add(cancelButton);
              // create exit button panel
              JPanel exitPanel = new JPanel();
              exitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
              // exit button
              exitButton = new JButton("Exit");
              exitButton.addActionListener(new ExitListener());
              exitPanel.add(exitButton);
              // add panels to the ButtonPanel
              setLayout(new BorderLayout());
              add(maintPanel, BorderLayout.CENTER);
              add(exitPanel, BorderLayout.SOUTH);
         public void setAddEditMode(boolean e)
              addButton.setEnabled(!e);
              editButton.setEnabled(!e);
              deleteButton.setEnabled(!e);
              acceptButton.setEnabled(e);
              cancelButton.setEnabled(e);
    class AddListener implements ActionListener
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         Player newPlayer;
         public void actionPerformed(ActionEvent e)
              newPlayer = new Player();
              playerPanel.clearFields();
              buttonPanel.setAddEditMode(true);
              playerPanel.setAddEditMode(true);
    class EditListener implements ActionListener
         ButtonPanel buttonPanel;
         PlayerDisplayPanel playerPanel;
         public void actionPerformed(ActionEvent e)
              buttonPanel.setAddEditMode(true);
              playerPanel.setAddEditMode(true);
    class DeleteListener implements ActionListener
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ArrayList<Player>team;
         public void actionPerformed(ActionEvent e)
              Player p = selectorPanel.getCurrentPlayer();
              team.remove(p);
              TeamIO.saveTeam();
              selectorPanel.fillComboBox(team);
              selectorPanel.selectPlayer(team.get(0));
              playerPanel.showPlayer(team.get(0));
              selectorPanel.playerComboBox.requestFocusInWindow();
    class AcceptListener implements ActionListener
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         ArrayList<Player>team;
         Player newPlayer;
         public void actionPerformed(ActionEvent e)
              if (isValidData())
                   if (newPlayer != null)
                        newPlayer = playerPanel.getPlayer();
                        team.add(newPlayer);
                        TeamIO.saveTeam();
                        selectorPanel.fillComboBox(team);
                        selectorPanel.selectPlayer(newPlayer);
                        newPlayer = null;
                   else
                        Player p = selectorPanel.getCurrentPlayer();
                        Player newPlayer = playerPanel.getPlayer();
                        p.setLastName(newPlayer.getLastName());
                        p.setFirstName(newPlayer.getFirstName());
                        p.setNumber(newPlayer.getNumber());
                        TeamIO.saveTeam();
                        selectorPanel.fillComboBox(team);
                        selectorPanel.selectPlayer(p);
                        playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
                   playerPanel.setAddEditMode(false);
                   buttonPanel.setAddEditMode(false);
                   selectorPanel.playerComboBox.requestFocusInWindow();
         public boolean isValidData()
              return SwingValidator.isPresent(playerPanel.lastNameTextField, "Last Name")
                   && SwingValidator.isPresent(playerPanel.firstNameTextField, "First Name")
                   && SwingValidator.isPresent(playerPanel.numberTextField, "Number")
                   && SwingValidator.isInteger(playerPanel.numberTextField, "Number");
    class CancelListener implements ActionListener
         Player newPlayer;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         teamSelectorPanel selectorPanel;
         public void actionPerformed(ActionEvent e)
              if (newPlayer != null)
                   newPlayer = null;
              playerPanel.setAddEditMode(false);
              playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
              buttonPanel.setAddEditMode(false);
              selectorPanel.playerComboBox.requestFocusInWindow();
    class ExitListener implements ActionListener
         public void actionPerformed(ActionEvent e)
              System.exit(0);
    class SwingValidator
         public static boolean isPresent(JTextComponent c, String title)
              if(c.getText().length()==0)
                   showMessage(c, title + " is a required field.\n" + "Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
              return true;
         public static boolean isInteger(JTextComponent c, String title)
              try
                   int i = Integer.parseInt(c.getText());
                   return true;
              catch(NumberFormatException e)
                   showMessage(c,title+" must be an integer.\n"+"Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
         private static void showMessage(JTextComponent c, String message)
              JOptionPane.showMessageDialog(c, message, "Invalid Entry", JOptionPane.ERROR_MESSAGE);
    }

  • How do I convert an int to a String?

    How do I convert an int to a String?

    You can also use any of these methods if you need to get more complicated:
    Integer.toString(int i)
    Integer.toBinaryString(int i)
    Integer.toHexString(int i)
    Integer.toOctalString(int i)
    Integer.toString(int i, int radix)

  • Convert an IP address into an integer

    Hi Everyone,
    One of methods in my COM object is
    public void setIP(Variant ip)
    with Variant data type supposes to be 4 byte int. I don't know how to convert a string like "192.167.1.108" to an int so I can pass in the above function. Would anybody please help me out!
    Someone helped me out with his sample, but for some reason, the sample did not work for all ip address. e.g 192.167.1.108, 192.167.2.1 etc.
    Here is someone's sample:
    static int ipToInt(String ip)
    StringTokenizer st = new StringTokenizer(ip, ".");     
    int numParts = st.countTokens();     
    if (numParts == 0)          
    throw new IllegalArgumentException("Invalid IP address: empty argument");     
    if (numParts > 4)          
    throw new IllegalArgumentException("Invalid IP address: too many tokens");     
    int ipInt = 0;          
    for (int i = 1; i < numParts; i++)     
    String token = st.nextToken();          
    int tokenVal = Integer.parseInt(token);          
    // Above will throw NumberFormatException if the token is not an integer          
    int processedVal = tokenVal << (8 * (4 - i));          
    // Moves the byte to the correct portion of the int          
    ipInt = ipInt + processedVal;     
    String token = st.nextToken();     
    int tokenVal = Integer.parseInt(token);     
    // Above will throw NumberFormatException if the token is not an integer     
    ipInt = ipInt + tokenVal;
    Thanks in advance
    Hung

    static long ipToInt(String ip)
    StringTokenizer st = new StringTokenizer(ip, ".");
    long numParts = st.countTokens();
    if (numParts == 0)
    throw new IllegalArgumentException("Invalid IP address: empty argument");
    if (numParts > 4)
    throw new IllegalArgumentException("Invalid IP address: too many tokens");
    long ipInt = 0;
    while (st.hasMoreTokens()) {
    long tokenVal = Integer.parseInt(st.nextToken());
    ipInt = (ipInt << 8) + tokenVal;
    // System.out.println(Long.toHexString(ipInt));
    return ipInt;

Maybe you are looking for