String to Int and Int to String
How can I convert a string to Int & and an Int to String ?
Say I've
String abc="234"
and I want the "int" value of "abc", how do I do it ?
Pl. help.
String.valueOf(int) takes an int and returns a string.
Integer.parseInt(str) takes a string, returns an int.
For all the others long, double, hex etc. RTFM :)
Similar Messages
-
Date from a string and int value in ssis
hi so my table is as follows
active expirymonth
expiryyear
0 October 2014
0 February 2015
1 January 2012
and so on
now my requirement is that if active =0 then in a new table lets say LASTDATE and they want a date with the last day of the expiry month and year and if active is anything else write NULL for eg
LASTDATE
10/31/2014
02/28/2015
NULL
I went to derived tables and made a new table called lastdate. What expression do i build in the expression builder to get the required result as i could not find a way to convert the text into int and then into a dateHi Bharatb111,
If you want to achieve this using Derived Columns transform, you have to use following expression to first convert the month name value to integer:
([expirymonth]==”January”)?1:([expirymonth]==“February”)?2: ([expirymonth]==”March”)?3:([expirymonth]==“April”)?4:5
However, if we need to validate a couple of or even all of twelve months, the expression validation will be failed. So, the Derived Column approach is impossible.
To achieve your goal, you can use a Script Component to perform the date format conversion. This way, we can convert “dd/MMMM/yyyy(such as “01/October/2014”) format string value to “MM/dd/yyyy” (such as “10/01/2014”), and assign this value to a new output
column (assuming its name is “DateVal” and its data type is DT_DATE) of the Script Component. Then, we can drag a Derived Column under the Script Component and connect them. In the Derived Column, we can add a new column named “LASTDATE” with the following
expression:
([active]==0)?DATEADD(“d”,-1, DATEADD(“Month”),1,DateVal]):NULL(DT_DATE)
For the Script Component code snippet, please refer to Reza’s answer:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/1661339c-252c-4197-9cfd-943e1d86b573/convert-a-string-to-date-format?forum=sqlintegrationservices
Hope this helps.
Regards,
Mike Yin
TechNet Community Support -
Hi everybody,
ive got a class that creates a new int. i want the name of the int to be a parameter that i can send into the class. so for example:
public testObject(String intName)
then in my main I could say:
testObject grader = new testObject(gradeOne);
and the testObject class would make a new int called gradeOne.
does anybody know how i could accomplish this?Well you can hava a java.util.Map that maps Strings (for the names) to Integers (for the values).
You could encapsulate that map within another class if you feel that helps the design, and provide a method that expresses the relationship pretty easily, e.g.,:
public class NamedInts {
private Map mapping = new HashMap();
public void addNumber(String name, int value) {
mapping.put(name, Integer.valueOf(value));
// other methods, presumably, as well
}Is that what you meant? -
How to read a C structure with string and int with a java server using sock
I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
I want to know how can I read strings and int with the same stream because they are sent at the same time:
C pgm sent structure :
char* chaine1;
char* chaine2;
int nb1;
int nb2;
I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
Any idea would be a good help...
thanks.
Nicolas (France)Does the server sent the ints in little endian or big endian format?
The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it. -
Read the file and write the data into string or int
Ok, here's another rookie question.
I got to read the line from the file and store it in the memory as string or integer.
I wrote this code:
File inputFile = new File("c:/xxx.yyy");
String outputString = new String();
FileReader c1 = new FileReader(inputFile);
StringWriter d1 = new StringWriter(outputString);
int data;
while((data = c1.read()) != -1)
d1.write(data);
System.out.println(data);
c1.close();
d1.close();This is how I see it, but it cannot be even compiled because there is no such thing as StringWriter(String) wich I find completely irrational. So tell me, am I retarded or what? No, but seriosly, please help the newbie to understand these streams, am I supposed to use some kind of buffer? Any help appreciated.A String is an immutable. You cannot update a String.
A new String() is basically the same as an empty String ""
An empty StringWriter can be created with new StringWriter().
If you use a BufferedReader you can call readLine().
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line = in.readLine()) != null) {
System.out.println(line);
} -
Kinda urgent please help pass strings to doubles and strings to ints
Need to know how to pass strings to doubles and strings to ints
and to check if a string is null its just if (name == null;) which means black right?
like size as a string and then make the string size a doublecupofjava666 wrote:
Need to know how to pass strings to doubles and strings to ints
and to check if a string is null its just if (name == null;) which means black right?
like size as a string and then make the string size a doubleThink he means blank.
Check the Wrapper classes (Double, Integer) in the api.
parseInt() parseDouble() both take a string and return a primitive.
String s = null;
if(s == null) should do the trick!
Regards.
Edited by: Boeing-737 on May 29, 2008 11:08 AM -
How do you test if a string could be a valid int and then convert to int?
Hello, my name is Esran41 and I'm new to this site. I'm in computer science one this year and our current assignment is to make a console based Tic-Tac-Toe game. The final program must be able to detect errors in the user's input. For example, if the program asked the user for an int and he typed a character, our program must recognize this, print an error message, and then prompt him for the int again. I also need to know some common string manipulation methods(like String.length) and their syntax too. Again, I'm extremely new to java, so please include code fragments and example programs to demonstrate these methods.
To sum-it-up, I need to know how to do the following(The syntax):
Method (1)
- test an inputed string to see if it's a valid integer
- report an error to the user if it's not a valid integer
- if there was an error, prompt the user again
Method (2)
- Pass the inputed string as a parameter
- Convert the string into an integer
- return the integer
Also, what is a try-catch statement, what does it do, and how is it implemented?
Please post any advice or help that you may have pertaining to my problems.
Thanks!Do not insult me. If I could read my computer science
book, I would. Please don't insult yourself... by pointing out your limitations...
I will apologize for my cynical remarks... You should see how many requests for " I need help" where the answer could be found so easily...
But it is quite obvious that you have access to the internet... If you did a search for Java, eventually you would find yourself as Sun's web site... Which means that you would have arrive at this page...
http://java.sun.com
and towards the bottom left had corner of that page you would find these links...
Learning
New to Java Center
- Tutorials & Code Camps
- Online Sessions & Courses
- Course Certification
- Instructor-Led Courses
- Quizzes
And you will find the same resources that I am using to learn Java...
I'm looking up this information not only for myself, but for my class too....
Thus, we are stuck with old computers, about twenty books for 220 kids, and one teacher who is great at >C++, but knows nothing about java.Then print out the Java documentation, goto Kinko's and make copies so that your class can have the reference material available to them, or ask your teacher to... Since he/she will need to learn the language also... But since they have programming experience they will be better able to explain the concepts of programming that you do not understand...
You can make any excuse for why it is difficult for you to learn, but in the end its totally irrelevant... If the school district cannot provide funding for class material, then instead of complaining with " I don't have a book... " start a community fund raiser to purchase those materials... Goto to the public library and see if they have resources you and your class can utilize... After all, it is your responsibility to educate yourself...
And most important of all, never ever say anything negative or limiting against yourself...
Do not insult me. If I could read my computer science book, I would. This is a statement against yourself... What does this statement tell you about yourself... You stated that I should not judge, but here you made a judgement about your own ability to learn...
To even insinuate that I skip class is an outrage to me. You should watch your tongue and not be so >quick to judge a situation.Why, do you ? Apparently I touched a nerve somewhere... But that does not matter...
Are you really concerned with what I think of you... If you are then you are a fool...
What other think or say have nothing to do with you... Do you know me, do I know you...
The answer is clear... I can give it to you... The Answer is No.
If you want to learn then learn... Read, Research, Practice and Read again... So simple...
Anyway... Have fun... Check out the tutorials, learn how to use the API documentation and practice coding...
and here are those links again...
The Java Tutorial
http://java.sun.com/docs/books/tutorial/index.html
Essentials of the Java Programming Language: A Hands-On Guide, Part 1 and 2
http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/
http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/
Language Essentials Short Course
http://java.sun.com/developer/onlineTraining/JavaIntro/contents.html
Others
The Java Tutorial
http://java.sun.com/docs/books/tutorial/index.html
Tutorial Index
http://java.sun.com/developer/onlineTraining/index.html
- MaxxDmg...
- ' He who never sleeps... ' -
Guys/Gals,
Here's an interesting problem to ponder...
I define the following values in my class:
private String descriptorClassName = null;
private String userObjectClassName = null;
private String name = null;
I run the following piece of code as part of the constructor:
descriptorClassName = this.getClass().getName();
userObjectClassName = descriptorClassName.substring(0, descriptorClassName.indexOf("Descriptor"));
name = userObjectClassName.substring(userObjectClassName.lastIndexOf(".")+1);
The first line assigns the value of "com.foo.user.UserDataDescriptor" to descriptorClassName.
The second line assigns the value of "com.foo.user.UserData" to userObjectClassName.
The third line assigns the value of "UserData" to name.
As I step through the code, I see the first two values being set, and yet the third value for name is reported by the debugger as:
"name = null".
I added a call to log4j, which reports that that value of name has been correctly set!
This seems to be a result of the String.substing(int) call, as the call to Sring(substring(int, int) is fine.
Has anyone come accross this one before?
Does anyone have any workarounds other than:
name = userObjectClassName.substring(userObjectClassName.lastIndexOf(".")+1, userObjectClassName.length());
Cheers all.
Regards,
Chris.I've been trying to reproduce this problem and it always works perfectly. The debugger tells me that name = "UserData". I'm using JDev 3.2.2 and my project is using JDK1.2.2_JDeveloper. Here's the exact source code I'm trying.
package com.foo.user;
public class UserDataDescriptor {
private String descriptorClassName = null;
private String userObjectClassName = null;
private String name = null;
public UserDataDescriptor() {
descriptorClassName = this.getClass().getName();
userObjectClassName = descriptorClassName.substring(0, descriptorClassName.indexOf("Descriptor"));
name = userObjectClassName.substring(userObjectClassName.lastIndexOf(".")+1);
System.out.println("end of constructor");
public static void main(String[] args) {
UserDataDescriptor userDataDescriptor = new UserDataDescriptor();
null -
I have a function from a dll that return a double* string and an integer. How can I call this function from LabVIEW? There is a possibility to work in LabVIEW with a double* string?
pcbv wrote:
> Hello all,<br><br>The header of the function is:
>
> "HRESULT WRAPIEnumerateDevices(WRAPI_NDIS_DEVICE **ppDeviceList, long *plItems);"
>
> where WRAPI_NDIS_DEVICE have this form:
>
> typedef struct WRAPI_NDIS_DEVICE<br>{<br>
> WCHAR *pDeviceName;<br>
> WCHAR *pDeviceDescription;<br><br>}
> WRAPI_NDIS_DEVICE;<br><br>
>
> The function is from WRAPI.dll, used for communication with wireless card.
> For my application I need to call in LabVIEW this function.
Two difficulties I can see with this.
First the application seems to allocate the array of references
internally and return a pointer to that array. In that case there must
be another function which then deallocates that array again.
Then you would need to setup the function call to have a pointer to an
int32 number for the deviceList parameter and another pointer to int32
one for the plItems parameter.
Then create another function in your DLL similar to this:
HRESULT WRAPIEnumExtractDevice(WRAPI_NDIS_DEVICE *lpDeviceList, long i,
CHAR lpszDeviceName, LONG lenDeviceName,
CHAR lpszDeviceDesc, LONG lenDeviceDesc)
if (!lpDeviceList)
return ERROR_INV_PARAMETER;
if (lpDeviceList[i].pDeviceName)
WideCharToMultiByte(CP_ACP, 0,
pDeviceList[i].pDeviceName, -1,
lpszDeviceName, lenDeviceName,
NULL, NULL);
if (lpDeviceList[i].pDeviceName)
WideCharToMultiByte(CP_ACP, 0,
pDeviceList[i].pDeviceDescription, -1,
lpszDeviceDesc, lenDeviceDesc,
NULL, NULL);
return NO_ERROR;
Pass the int32 you got from the first parameter of the previous call as
a simple int32 passed by value to this function (and make sure you don't
call this function with a higher index than (plItems - 1) returned from
the first function.
Rolf Kalbermatter
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions -
Parsing a string to formula and executing to int value
Hi ,
I have a String from the database which will hold symbols + - etc.
Eg: String a =((((2+5)/(80*76)) -65)*)The above shows a string with operators and numeric values. I need to execute this String and obtain a integer value.
How i can accomplish this. From database ill be getting may different string with different formula values.
Any help is highly appreciated.
Thanks in advance.
Regards,
Satheesh Kannan.A.BWe already have [this post|http://forums.sun.com/thread.jspa?threadID=5144807],
may also try [this link|http://sourceforge.net/projects/expression-tree/]. -
Composite Primary Key with two KeyField: One string and one sequential int.
Hi All,
Acording to [url http://download.oracle.com/docs/cd/E17277_02/html/java/com/sleepycat/persist/model/PrimaryKey.html#sequence()]sequence JavaDoc: A composite key class may also be used to override sort order, but it may contain only a single key field that has one of the types previously mentioned.
We are trying to create a composite PK like the following:
@Persistent
public class ExamplePK {
@KeyField(1) Integer seq;
@KeyField(2) String admon;
public String getAdmon() {
return admon;
public void setAdmon(final String admon) {
this.admon = admon;
public Integer getSeq() {
return seq;
public void setSeq(final Integer seq) {
this.seq = seq;
@Entity
public class ExamplePojo {
// Relational fields
@PrimaryKey(sequence="ExampleSeq")
private ExamplePK idExample;
public ExamplePK getIdExample() {
return idExample;
public void setIdExample(final ExamplePK idExample) {
this.idExample = idExample;
}but we are getting the following exception:
java.lang.IllegalArgumentException:A composite key class used with a sequence may contain only a single integer key field: es.correos.ape.dao.notification.pojo.ExamplePK[Server1:1291138230743]
at com.sleepycat.persist.impl.CompositeKeyFormat.getSequenceKeyFormat(CompositeKeyFormat.java:292)
at com.sleepycat.persist.impl.PersistKeyAssigner.<init>(PersistKeyAssigner.java:39)
at com.sleepycat.persist.impl.Store.getPrimaryIndex(Store.java:337)
at com.sleepycat.persist.EntityStore.getPrimaryIndex(EntityStore.java:307)What are we doing wrong?
BR,
/César.Hi Cesar,
I think you may be misunderstanding the doc.
A composite key class may also be used to override sort order, but it may contain only a single key field that has one of the types previously mentioned.This means that if you have a sequence, you can only have one key field. In the code you posted, you're defining two key fields.
java.lang.IllegalArgumentException:A composite key class used with a sequence may contain only a single integer key field: es.correos.ape.dao.notification.pojo.ExamplePK[Server1:1291138230743]This is telling you that you cannot have more than one key field, when using a sequence.
--mark -
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 AMOk. 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);
} -
Hi,
when i try to do the following its an error
int totalmarks;
String Totalmarks;
Totalmarks = totalmarks.toString();
could any one tell me how to do it correctly
Thank youA lot of alternatives, but you can't do new String(int..).
1. Integer.toString(totalmarks)
2. String.valueOf(totalmarks) will call Integer.toString(totalmarks)
3. ""+totalmarks will use the StringBuffer and append "" and totalmarks which again will call String.valueOf(totalmarks) which again will call Integer.toString(totalmarks) -
i want to know how to convert an int to a string .
I have tried toString() but it says can't dereference an int.
any ideas ????
thanksWhat I mean by the object being null is, say for example, you have the following method:
public String combine(Object o1, Object o2){
return o1.toString() + o2.toString();
}This method will throw a NullPointerException if either or both o1 and/or o2 are null. If you use it like so:
public String combine(Object o1, Object o2){
return String.valueOf(o1) + String.valueOf(o2);
}This will always work. (I know someone out there would say that this would return a String like "nullnull" if both are null, and so forth and so on, but hey, you get my drift.) I'm also not saying the you can't not check if either o1 or o2 is null before proceeding, so the following also works:
public String combine(Object o1, Object o2){
String s = null; // I'm using this instead of StringBuffer for
// simplicity's sake so don't get this wrong
if (o1 != null){
s = o1.toString();
if (o2 != null){
s += o2.toString();
return s;
}As you can see, there's no right or wrong way in programming as long as you achieve the result. The only thing that would matter is how clean your code is, how efficient your code is, and how maintainable your code is. -
Convert a string of an array to an int
I want to convert numbers[k] which is a string array to an int. How can i do this. I have tried everyting on the net I can find but not much help
This is my code and I still get a complier error of found: String
required:int
public void squares()
{System.out.println(stringNumbers.length);
for (int k=3;k<=4;k++)
{ System.out.println("the value of k is "+k);
sqCount++;
//int sqsize= (Integer) stringNumbers[k].valueOf(sqsize);
for (int p=0;p<=stringNumbers.length;p++)
{ String str=stringNumbers[p];
Integer.parseInt(str);
for(int i=0;i<=4;i++)
{ xcord=i;
for(int j=0;j<=4;j++)
{ ycord=j;
if(xcord+stringNumbers[k]<=stringNumbers[2]&& ycord+stringNumbers[k]<=stringNumbers[2])
{ //creating an array for each set of sqNum,xcord,ycord
System.out.println(sqCount+" "+xcord+" "+ycord);
else
{ System.out.print("");
}
Maybe you are looking for
-
I deleted my pics on my ipod by mistake, how do I get them back?
-
Internal error 224: couldn't create /initialize the LogosManager
We keep getting an error window on boot-up: "The DataFinder cannot start due to an internal error. (224): Couldn't create/initialize the LogosManager Any ideas?
-
Hi, I got following email from Oracle, but I can see only 1zo-051 and 1zo-052 exam results. Congratulations on earning your Oracle Certification credential! To provide you with immediate access to your certification credential, you can now download
-
Adjustment Layer For Audio Effects
We've the latest Adjustment Layer For Video Fx In Premiere now days.....but my question is Did premiere have anything like Adjustment Layer....So Basically if you want to add 20 Sound Effects in 40 Clips You gonna spend the whole day for doing that..
-
How to find the parameters names of a method using reflection?
Hi, Using the function getParameterTypes(), it is possible to find all parameter types from a Method. However, is there a way to find all parameters NAMES of a Method? If the asnwer is no, is there an easy way to obtain this information using the jav