Please help if you have time
I'm trying to write a program that will take employee entries using JOptionPane and then display the list. It's still in its early stages, but I'm already having issues. After I finish adding my entries, it only prints the line "The list contains:" I can't get it to print the contents of the array. I'm not real familiar with using JOptionPane in regards to arrays. Any help would be greatly appreciated.
Methods
import javax.swing.*;
publicclass SquiresMethod
{
publicstaticint START_POSITION = 1;
publicstaticint DEFAULT_SIZE = 50;
//entry.length is the total number of items you have room
//for on the list. countOfEntries is the number of items
//currently on the list.
privateint countOfEntries;//our counter -- must be less than entry.length.
private String[] entry;//our array
public SquiresMethod(int maximumNumberOfEntries)// constructor
{
entry =new String[maximumNumberOfEntries];
countOfEntries = 0;
}
/**
Creates an empty list with a capacity of DEFAULT_SIZE.
*/
public SquiresMethod( )// constructor
{
entry =new String[DEFAULT_SIZE];
countOfEntries = 0;
}
publicboolean full( )// we use this method in ListDemo
{
return (countOfEntries == entry.length);
}
publicboolean empty( )
{
return (countOfEntries == 0);
}
/**
Precondition: List is not full.
Postcondition: If item was not on the list,
it has been added to the list.
*/
publicvoid addItem(String item)
{
if (! onList(item))
{
if (countOfEntries == entry.length)
{
System.out.println("Adding to a full list!");
System.exit(0);
}
else
{
entry[countOfEntries] = item;
countOfEntries++;
}
}//else do nothing. Item is already on the list.
}
/**
If the argument indicates a position on the list,
then the entry at that specified position is returned;
otherwise, null is returned.
*/
public String getEntryAt(int position)// used for printing entire list, for example
{
if ((1 <= position) && (position <= countOfEntries))
return entry[position - 1];
else
returnnull;
}
/**
Returns true if position is the index of the
last item on the list; otherwise, returns false.
*/
publicboolean atLastEntry(int position)
{
return (position == countOfEntries);
}
/**
Returns true if item is on the list;
otherwise, returns false. Does not differentiate
between upper- and lowercase letters.
*/
publicboolean onList(String item)// Searches list for item
{
boolean found =false;
int i = 0;
while ((! found) && (i < countOfEntries))
{
if (item.equalsIgnoreCase(entry[i]))
found =true;
else
i++;
}
return found;
}
publicint maximumNumberOfEntries( )
{
return entry.length;
}
publicint getNumberOfEntries( )
{
return countOfEntries;
}
publicvoid eraseList( )
{
countOfEntries = 0;
}
}
MAIN METHOD
import java.util.*;
import javax.swing.*;
publicclass SquiresProject3
{
publicstaticvoid main(String[] args)
{
SquiresMethod employeeList =new SquiresMethod();
boolean more =true;
String next = null, ans =null;
while ( more && (! employeeList.full( )))
{
JOptionPane.showInputDialog("Please enter the employee name");
if (employeeList.full( ))
{
JOptionPane.showMessageDialog(null,"The list is full");}
else
{
ans =
JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim( ).equalsIgnoreCase("no"))
more =false;
}
}
JOptionPane.showMessageDialog(null,"The list contains:");
int position = employeeList.START_POSITION;
next = employeeList.getEntryAt(position);
while (next !=null)
{
System.out.println(next);
position++;
next = employeeList.getEntryAt(position);
}
}
}
I'm really tired right now, so this code may be beyone simple suggestions. But, any help would be really appreciated.
Thanks a lot
[8835 byte] By [
dazemana] at [2007-11-27 11:41:05]

Hi
public static void main(String[] args)
{
SquiresMethod employeeList = new SquiresMethod();
boolean more = true;
String next = null, ans = null;
String name;
int i=0;
while ( more && (! employeeList.full( )))
{
name = JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem (name);
if (employeeList.full( ))
{
-
you have to add these marked (bold) lines, you will get what you want
//other codes are same
Thanks for the suggestion, upon adding the code I get:
SquiresProject3.java:34: variable name might not have been initialized
employeeList.addItem(name);
If I add it as String name = null , the program will compile, but it ends after I enter the second employee name:
Exception in thread "main" java.lang.NullPointerException
at SquiresMethod.onList(SquiresMethod.java:108)
at SquiresMethod.addItem(SquiresMethod.java:60)
at SquiresProject3.main(SquiresProject3.java:34)
There may be some other issues with my code. If you have any other suggestions I'd greatly appreciate it
THanks
first do String name = "";
looks much nicer and doesn't add null to the front :) second where did you add that code?
>SquiresProject3.java:34: variable name might not have been initialized
>employeeList.addItem(name);
initialized it.
String name = "";
boolean more = true;
String next = null, ans = null;
String name = "";
{
//Creates 4 buttons for the different operations
Object[] options = { "Add new employee ", "delete employee", "Search for employee name" };
int select = JOptionPane.showOptionDialog(null, "What operation do you want to perform", "Choose an option", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
switch (select) {
case 0:
while ( more && (! employeeList.full( ))){
JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem(name);
if (employeeList.full( ))
{
JOptionPane.showMessageDialog(null, "The list is full");}
else
{
ans =
JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim( ).equalsIgnoreCase("no"))
more = false;
}
}
break;
Thanks for that tip. It seems to run fine now but as soon as I say that I don't have another entry, it just displays "List Contains" and then it ends without showing what the list contains. I'm thinking that maybe I made the method wrong or something. All of the examples I have always seem to use solely System.out.print for everything, but I like to use JOptionPane which always makes it a little more difficult I guess. Anyways, thanks so much for taking the time to try and help
> > JOptionPane.showMessageDialog(null, "The list
> list contains:");
>int position = employeeList.START_POSITION;
>next = employeeList.getEntryAt(position);
>
> while (next != null)
> {
> System.out.println(next);
> position++;
> next =
> employeeList.getEntryAt(position);
> }
>
You do know your not printing the text in a JOptionPane box right? your just printing it in your output screen
ok well the text doesn't print though lol ima look at the code closer
Message was edited by:
mark07
Yeah, I changed it to the following:
int position = employeeList.START_POSITION;
next = employeeList.getEntryAt(position);
JOptionPane.showMessageDialog(null, "The list contains:" + next);
while (next != null)
{
position++;
next = employeeList.getEntryAt(position);
JOptionPane.showMessageDialog(null, (next));;
It's still only printing "The list contains"
I'm sorry for my ignorance; I really have no experiencing trying to print through JOptionPane using arrays. Can anyone see why I'm not printing the list?
Thanks so much
can you show me in what you posted where you called .additem? :) try this
String next = "", ans = "", name = "";
while ( more && (! employeeList.full( )))
{
name = JOptionPane.showInputDialog("Please enter the employee name");
if (employeeList.full( ))
{
JOptionPane.showMessageDialog(null, "The list is full");}
else
{
employeeList.addItem(name);
ans =
JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim( ).equalsIgnoreCase("no"))
more = false;
}
}
Thanks for the suggestion:
boolean more = true;
boolean runagain;
String next = "", ans = "", name = "";
//Creates 4 buttons for the different operations
Object[] options = { "Add new employee ", "delete employee", "Search for employee name" };
do{
int select = JOptionPane.showOptionDialog(null, "What operation do you want to perform", "Choose an option", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
switch (select) {
case 0:
while ( more && (! employeeList.full( ))){
JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem(name);
if (employeeList.full( ))
{
JOptionPane.showMessageDialog(null, "The list is full");}
else
{
employeeList.addItem(name); ans = JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim( ).equalsIgnoreCase("no"))
more = false;
}
}
Still printing blank JOptionPane. I think I must have something messed up with the print
int position = employeeList.START_POSITION;
next = employeeList.getEntryAt(position);
JOptionPane.showMessageDialog(null, "The list contains:" + next);
while (next != null)
{
position++;
next = employeeList.getEntryAt(position);
JOptionPane.showMessageDialog(null, (next));;
}select = JOptionPane.showConfirmDialog(null, "Run Again?", "Run Again Dialog",JOptionPane.YES_NO_OPTION);
//if yes is selected "runagain" equates to true if no is selected "runagain" equates to false
runagain = (select == JOptionPane.YES_OPTION);
} while (runagain); //end of main do-while loop
give me a few minutes I'm kinda reworking your program to be more efficent if you don't mind
Certainly not dude. I'm a bit of a begginner if you hadn't guessed...hehe. I've been building computers and fixing them at work for years, so I never figured I'd suck so much at programming. Guess I just don't have enough time to study to the extent that's necessary. I really appreciate you taking the time to assist me with this
Thanks
lol no problem man I'm almost done just fixing up 1 more thing sorry I'm at work so i gota switch between **** :)
FYI: The requirements for this project are: Your program can add, delete, search and list (traverse and print all records). For the program, 10 records is maximum, with 3-4 sufficient for testing purposes. In adding, no duplicates (customer names) are allowed. When listing, records should be in sorted order.
Just thought you should know what my intentions were if you're rewriting some of it. I realize I haven't added all of these capabilities yet, but I'm just trying to get the foundation working first. I like to see that I have a working menu and some functions working before I suffice all requirements
Thanks
cool, can I ask what you do? Are you currently working in a programming job or are you also studying? :)
Try this code and see if it's what you want:
import java.util.*;
import javax.swing.*;
public class SquiresProject3 {
public static void main(String[] args) {
SquiresMethod employeeList = new SquiresMethod();
boolean more = true;
String next = null,
ans = null;
JOptionPane.showInputDialog("Please enter the employee name");
while ( more && !employeeList.full() ) {
ans = JOptionPane.showInputDialog("Would you like to make another entry?");
if ( ans.trim().equalsIgnoreCase("no") ) {
more = false;
break;
}
next = JOptionPane.showInputDialog("What is this employees name?");
employeeList.addItem(next);
}
if ( employeeList.full() )
JOptionPane.showMessageDialog(null, "The list is full");
JOptionPane.showMessageDialog(null, "The list contains:");
int position = employeeList.START_POSITION;
while ( ( next = employeeList.getEntryAt(position) ) != null ) {
System.out.println(next);
position++;
next = employeeList.getEntryAt(position);
}
}
Or simplify the while:
while ( more && !employeeList.full() ) {
next = JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem(next);
ans = JOptionPane.showInputDialog("Would you like to make another entry?");
if ( ans.trim().equalsIgnoreCase("no") ) {
more = false;
break;
}
}
Message was edited by:
abillconsl
public static void main(String [] args){
SquiresMethod employeeList = new SquiresMethod();
boolean more = true;
String next = "", ans = "", name = "";
while ( more && (! employeeList.full( )))
{
name = JOptionPane.showInputDialog("Please enter the employee name");
if (employeeList.full())
{
JOptionPane.showMessageDialog(null, "The list is full");
}
else
{
employeeList.addItem(name);
ans = JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim().equalsIgnoreCase("no") || ans.trim().equalsIgnoreCase("n"))
more = false;
}
}
JOptionPane.showMessageDialog(null, "The list contains:");
for(int x = 0; x < employeeList.getNumberOfEntries(); x++) {
next += employeeList.getEntryAt(x) + " ";
}
JOptionPane.showMessageDialog(null,"The names " + next);
}
import javax.swing.JOptionPane;
/**
*
* @author
*/
public class SquiresMethod
{
public static int START_POSITION = 0;
public static int DEFAULT_SIZE = 50;
//entry.length is the total number of items you have room
//for on the list. countOfEntries is the number of items
//currently on the list.
private int countOfEntries; //our counter -- must be less than entry.length.
private String[] entry;//our array
public SquiresMethod(int maximumNumberOfEntries)// constructor
{
entry = new String[maximumNumberOfEntries];
countOfEntries = 0;
}
/**
Creates an empty list with a capacity of DEFAULT_SIZE.
*/
public SquiresMethod( )// constructor
{
entry = new String[DEFAULT_SIZE];
countOfEntries = 0;
}
public boolean full( )// we use this method in ListDemo
{
return (countOfEntries == entry.length);
}
public boolean empty( )
{
return (countOfEntries == 0);
}
/**
Precondition: List is not full.
Postcondition: If item was not on the list,
it has been added to the list.
*/
public void addItem(String item)
{
if (!onList(item))
{
if (countOfEntries == entry.length)
{
System.out.println("Adding to a full list!");
System.exit(0);
}
else
{
entry[countOfEntries] = item;
countOfEntries++;
}
}//else do nothing. Item is already on the list.
//JOptionPane.showInternalConfirmDialog(null, "Item already on the list! didn't add");
}
/**
If the argument indicates a position on the list,
then the entry at that specified position is returned;
otherwise, null is returned.
*/
public String getEntryAt(int position)// used for printing entire list, for example
{
if (position <= countOfEntries)
return (entry[position]);
else
return " ";
}
/**
Returns true if position is the index of the
last item on the list; otherwise, returns false.
*/
public boolean atLastEntry(int position)
{
return (position == countOfEntries);
}
/**
Returns true if item is on the list;
otherwise, returns false. Does not differentiate
between upper- and lowercase letters.
*/
public boolean onList(String item)// Searches list for item
{
boolean found = false;
int i = 0;
while ((! found) && (i < countOfEntries))
{
if (item.equalsIgnoreCase(entry[i]))
{
found = true;
break;
}
else
i++;
}
return found;
}
public int maximumNumberOfEntries( )
{
return entry.length;
}
public int getNumberOfEntries( )
{
return countOfEntries;
}
public void eraseList( )
{
countOfEntries = 0;
}
}
There that should work need me to add anything? or explain? and I'm a itern programmer for Lexis-Nexis right now Im doing SQL code with databases but i just graduated high school and haven't started college yet so i got a lot to learn
Do this small change to list the employees:
public class SquiresProject3
{
public static void main(String[] args)
{
SquiresMethod employeeList = new SquiresMethod();
boolean more = true;
String next = null, ans = null;
String list = " ";
while ( more && (! employeeList.full( ))) {
String name = JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem (name);
if (employeeList.full( ))
JOptionPane.showMessageDialog(null, "The list is full");
else
{
ans =JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim( ).equalsIgnoreCase("no"))
more = false;
}
}
// JOptionPane.showMessageDialog(null, "The list contains:");
int position = employeeList.START_POSITION;
next = employeeList.getEntryAt(position);
while (next != null) {
list = list+ next +" ";
System.out.println(next);
position++;
next = employeeList.getEntryAt(position);
}
JOptionPane.showMessageDialog(null, "The list contains:"+list);
}
}
did that do what you wanted?
actually, I kept getting an error when I tried to use the method class you made. Of course, I didn't use the main that you made because I'm trying to use case statements for buttons and I'm still trying to figure out how to throw your code in while preserving my structure.
I was getting these errors after I adopted the method class you made:
Exception in thread "main" java.lang.RuntimeException: JOptionPane: parentComponent does not have a valid parent
at javax.swing.JOptionPane.createInternalFrame(JOptionPane.java:1486)
at javax.swing.JOptionPane.showInternalOptionDialog(JOptionPane.java:1259)
at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:1194)
at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:1155)
at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:1118)
at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:1090)
at SquiresMethod.addItem(SquiresMethod.java:40)
at SquiresProject3.main(SquiresProject3.java:38)
Maybe would work if I used your main, I'm going to play with it a little more. It's 1 AM here, so I'm starting to get a little bit stupid..hehe
I've got it printing now, but it prints :
The list contains: "first name entered"
and then if you hit enter it will display the next name...etc
How would I display all the names in the list in one JOptionPane box?
hey dazeman did you try the code that I gave you.
just make changes in your main and it will work fine.
when you ask for help look through the help you got.
StringBuffer buffy = new StringBuffer();
/* ... */
while ( ( next = employeeList.getEntryAt(position++) ) != null ) {
System.out.println(next);
if (next != null)
buffy.append(next+"\n");
}
JOptionPane.showMessageDialog(null, buffy.toString());
<Maybe would work if I used your main, I'm going to play with it a little more. It's 1 AM here, so I'm starting to get a little bit stupid..hehe
you have to use my entire main and the entire class i posted minus the package name becuase i changed stuff thoughout both... i ran them and they work fine>
Sorry, I didn't notice your post. I tried what you suggested and it printed:
"The list contains: "first entry"
followed by another box with first and second entry
followed by another box with first, second, third etc.
Maybe I did something wrong but I think I used your code exactly. I'm trying to print one list with all the entires at once
Thanks for the post, sorry I didn't notice it at first
for(int x = 0; x < employeeList.getNumberOfEntries(); x++) {
next += employeeList.getEntryAt(x) + " ";
}
JOptionPane.showMessageDialog(null,"The names " + next);
that's what it should be.... make sure the JOptionPane.showMessageDialog(null, "The names " + next); is outside of the for loop i think you have it inside
> Sorry, I didn't notice your post. I tried what you
> suggested and it printed:
> "The list contains: "first entry"
> followed by another box with first and second entry
> followed by another box with first, second, third
> etc.
>
> Maybe I did something wrong but I think I used your
> code exactly. I'm trying to print one list with all
> the entires at once
>
> Thanks for the post, sorry I didn't notice it at first
Notice my post? Bottom of prev page.
> > Sorry, I didn't notice your post. I tried what you
> > suggested and it printed:
> > "The list contains: "first entry"
> > followed by another box with first and second
> entry
> > followed by another box with first, second, third
> > etc.
> >
> > Maybe I did something wrong but I think I used
> your
> > code exactly. I'm trying to print one list with
> all
> > the entires at once
> >
> > Thanks for the post, sorry I didn't notice it at
> first
>
> Notice my post? Bottom of prev page.
Yeah, I was replying to you. Sorry, should have quoted your text. I tried your suggestion and above is the result. Maybe I did something wrong
Thanks
> mine didn't work?
Actually I finally did get it working with my other code. Works Great! One problem is that it attaches null to the first employee name.
Names are : Johnnull robert Albert
Name is John
Probably something simple; any suggestions?
Thanks dude
I'm trying to get the search function working now, but it seems to be telling me that the name is in the database when it isn't:
case 2:
String search =
JOptionPane.showInputDialog("Please enter the employee name");
employeeList.onList(item);
if
(found = true)
{
JOptionPane.showMessageDialog(null, search + " is in the list");
}
else
{
JOptionPane.showMessageDialog(null, search + " is not an employee");
}
break;
Method:
public boolean onList(String item)// Searches list for item
{
boolean found = false;
int i = 0;
while ((! found) && (i < countOfEntries))
{
if (item.equalsIgnoreCase(entry[i]))
found = true;
else
i++;
}
return found;
}
ya in your class .getentryat it should look like this if (position <= countOfEntries)
return (entry[position]);
else
return " ";
does it?
String search =
JOptionPane.showInputDialog("Please enter the employee name");
employeeList.onList(item);
look at what your storing the name your searching for to and what your passing to search for.... should be
employeeList.onList(item)
Message was edited by:
mark07
> ya in your class .getentryat it should look like this
> if (position <= countOfEntries)
> return (entry[position]);
>
>return " ";
Ok, I fixed that and it doesn't print the null, but it prints the last entry twice.
If names are: Albert, John, Roger
Prints: RogerAlber, John, Roger
> String search =
> JOptionPane.showInputDialog("Please enter the
> employee name");
>
> employeeList.onList(item);
> look at what your storing the name your searching for
> to and what your passing to search for.... should be
>
> employeeList.onList(item)
>
> Message was edited by:
> mark07
Sorry but I'm not sure that I understand what you mean. I thought that the method onLIst is returning a true if the names exists and false if it doesn't. I guess that I'm really confused about how that works.
ok well maybe post the code you have now so i can compare it to what i gave you? so i can see what's different
> > String search =
> > JOptionPane.showInputDialog("Please enter the
> > employee name");
> >
> > employeeList.onList(item);
> > look at what your storing the name your searching
> for
> > to and what your passing to search for.... should
> be
> >
> > employeeList.onList(item)
> >
> > Message was edited by:
> > mark07
>
>
> guess that I'm really confused about how that works.
My fault i posted the code wrong... second part should be employeeList.onList(search);
No your correct but you pass onList a String to check it against the list... only problem is you don't pass it the name you want to find you pass it item it should be search sorry i didn't explain it throughouly
Message was edited by:
mark07
For the record - here's the complete class:import java.util.*;
import javax.swing.*;
public class SquiresProject3 {
public static void main(String[] args) {
SquiresMethod employeeList = new SquiresMethod();
boolean more = true;
String next = null,
ans = null;
StringBuffer buffy = new StringBuffer();
while ( more && !employeeList.full() ) {
next = JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem(next);
ans = JOptionPane.showInputDialog("Would you like to make another entry?");
if ( ans.trim().equalsIgnoreCase("no") ) {
more = false;
break;
}
}
if ( employeeList.full() )
JOptionPane.showMessageDialog(null, "The list is full");
JOptionPane.showMessageDialog(null, "The list contains:");
int position = employeeList.START_POSITION;
while ( ( next = employeeList.getEntryAt(position++) ) != null ) {
System.out.println(next);
if (next != null)
buffy.append(next+"\n");
}
JOptionPane.showMessageDialog(null, buffy.toString());
System.exit(0);
}
}
ya but what is he using? becuase i gave him a main and a class earlier
> ya but what is he using? becuase i gave him a main
> and a class earlier
I'm using most of yours now, I just adapted it to the break statements and booleans I had written since we've been talking. It's working great now accept for the problem I mentioned about the last entry repeating at the begginning of the list.
Also, I tried to swap out the item for search, but it still seems to think that every name in the world exists in the database.
Here's what my code looks like now:
MAIN:
import java.util.*;
import javax.swing.*;
public class SquiresProject3
{
public static void main(String[] args)
{
SquiresMethod employeeList = new SquiresMethod();
boolean more1 = true, more2 = true, found = false;
boolean runagain;
String next = "", ans = "", list = "";
//Creates 4 buttons for the different operations
Object[] options = { "Add new employee ", "Delete employee", "Search for an employee name", "Display employee list" };
do{
int select = JOptionPane.showOptionDialog(null, "What operation do you want to perform", "Choose an option", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
switch (select)
{ case 0:
while ( more1 && (! employeeList.full( )))
{
next = JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem(next); if (employeeList.full( ))
{ JOptionPane.showMessageDialog( null, "The list is full"); }
else { employeeList.addItem(next);
ans = JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim( ).equalsIgnoreCase("no"))
more1 = false;
}
}
break;
case 1:
break;
case 2:
while (more2)
{
String search =
JOptionPane.showInputDialog("Please enter the employee name");
employeeList.onList(search);
if
(found = true)
{
JOptionPane.showMessageDialog(null, search + " is in the list");
}
else
{
JOptionPane.showMessageDialog(null, search + " is not an employee");
}
ans = JOptionPane.showInputDialog("Would you like to perform another search?");
if (ans.trim( ).equalsIgnoreCase("no"))
more2 = false;
}
break;
case 3:
for(int x = 0;
x < employeeList.getNumberOfEntries(); x++)
{
next += employeeList.getEntryAt(x) + ", ";
}
JOptionPane.showMessageDialog(null,"The list of employee names is: " + next);
break;
}
select = JOptionPane.showConfirmDialog(null, "Return to main menu?", "Run Again Dialog", JOptionPane.YES_NO_OPTION); //if yes is selected "runagain" equates to true if no is selected "runagain" equates to false
runagain = (select == JOptionPane.YES_OPTION);
} while (runagain); //end of main do-while loop
}
}
Method Class:
import java.util.*;
import javax.swing.*;
public class SquiresMethod
{
public static int START_POSITION = 1;
public static int DEFAULT_SIZE = 10;
//entry.length is the total number of items you have room
//for on the list. countOfEntries is the number of items
//currently on the list.
private int countOfEntries; //our counter -- must be less than entry.length.
private String[] entry;//our array
public SquiresMethod(int maximumNumberOfEntries)// constructor
{
entry = new String[maximumNumberOfEntries];
countOfEntries = 0;
}
/**
Creates an empty list with a capacity of DEFAULT_SIZE.
*/
public SquiresMethod( )// constructor
{
entry = new String[DEFAULT_SIZE];
countOfEntries = 0;
}
public boolean full( )// we use this method in ListDemo
{
return (countOfEntries == entry.length);
}
public boolean empty( )
{
return (countOfEntries == 0);
}
/**
Precondition: List is not full.
Postcondition: If item was not on the list,
it has been added to the list.
*/
public void addItem(String item)
{
if (! onList(item))
{
if (countOfEntries == entry.length)
{
System.out.println("Adding to a full list!");
System.exit(0);
}
else
{
entry[countOfEntries] = item;
countOfEntries++;
}
}//else do nothing. Item is already on the list.
}
/**
If the argument indicates a position on the list,
then the entry at that specified position is returned;
otherwise, null is returned.
*/
public String getEntryAt(int position)// used for printing entire list, for example
{
if (position <= countOfEntries)
return (entry[position]);
else
return " ";
}
/**
Returns true if position is the index of the
last item on the list; otherwise, returns false.
*/
public boolean atLastEntry(int position)
{
return (position == countOfEntries);
}
/**
Returns true if item is on the list;
otherwise, returns false. Does not differentiate
between upper- and lowercase letters.
*/
public boolean onList(String item)// Searches list for item
{
boolean found = false;
int i = 0;
while ((! found) && (i < countOfEntries))
{
if (item.equalsIgnoreCase(entry[i]))
found = true;
else
i++;
}
return found;
}
public int maximumNumberOfEntries( )
{
return entry.length;
}
public int getNumberOfEntries( )
{
return countOfEntries;
}
public void eraseList( )
{
countOfEntries = 0;
}
}
Sorry about the indentation; I have a habbit of leaving in crappy until I get the code working. Would probably be easier to read if I corrected it along the way, but I get in a rush to get it working.
Thanks a lot
I think he tried my version and had problems and tried your vers and got it to work, but he should have been able to get my version to work as well, so I wanted to be sure he knows what the differences are and what makes one work and when and how and all that ... blah blah blah ;o)
> I think he tried my version and had problems and
> tried your vers and got it to work, but he should
> have been able to get my version to work as well, so
> I wanted to be sure he knows what the differences are
> and what makes one work and when and how and all that
> ... blah blah blah ;o)
yeah, that's exactly what happened. I really appreciate your contribution though. I'm sure your code works great if I was compotent enough to utilize it...hehe. It's almost 4AM here, so I can barely see the screen anymore. I was able to get his working easier so that's what I used. But, I really appreciate you taking the time to contribute. So far, I feel like I've taken and extra semester of Java tonight
;)
ok i figured you used some of both becuase they both would work... don't edit the code ill look at it and post the whole thing since you can barely see :)
> > I think he tried my version and had problems and
> > tried your vers and got it to work, but he should
> > have been able to get my version to work as well,
> so
> > I wanted to be sure he knows what the differences
> are
> > and what makes one work and when and how and all
> that
> > ... blah blah blah ;o)
>
> yeah, that's exactly what happened. I really
> appreciate your contribution though. I'm sure your
> code works great if I was compotent enough to utilize
> it...hehe. It's almost 4AM here, so I can barely see
> the screen anymore. I was able to get his working
> easier so that's what I used. But, I really
> appreciate you taking the time to contribute. So far,
> I feel like I've taken and extra semester of Java
> tonight
> ;)
"It's almost 4AM here, so I can barely see the screen anymore."
Yipes! ... ya gotta love it, huh? Well you're certainly welcome. Now go get some sleep and stay off the roads until at least noon tomorrow, please!
that's college life for ya =)
> > > I think he tried my version and had problems and
> > > tried your vers and got it to work, but he
> should
> > > have been able to get my version to work as
> well,
> > so
> > > I wanted to be sure he knows what the
> differences
> > are
> > > and what makes one work and when and how and all
> > that
> > > ... blah blah blah ;o)
> >
> > yeah, that's exactly what happened. I really
> > appreciate your contribution though. I'm sure your
> > code works great if I was compotent enough to
> utilize
> > it...hehe. It's almost 4AM here, so I can barely
> see
> > the screen anymore. I was able to get his working
> > easier so that's what I used. But, I really
> > appreciate you taking the time to contribute. So
> far,
> > I feel like I've taken and extra semester of Java
> > tonight
> > ;)
>
> "It's almost 4AM here, so I can barely see the
> screen anymore."
>
> Yipes! ... ya gotta love it, huh? Well you're
> certainly welcome. Now go get some sleep and stay off
> the roads until at least noon tomorrow, please!
heheh...Wish I could, but I gotta get it delete entries and sort in order first. I need to make a method that will allow the user to either choose a name from the list or search for one and then delete it. Not sure how I wanna try and do that yet. I just wanted to see the main functions working before I tackled that beast. Maybe it's not that difficult, but it's all new to me so the simplest tasks are challenging. I'm trying to knock this out tonight cuz I got a big poker tounrament tomorrow afternoon. There's a game that I'm more familiar with ;)
> that's college life for ya =)
lol...yeah. Considering I'm in the Air Force so I work 12 hour days Mon-Fri and I'm always on call too. I should have worked on this last week, but sh*t was in the mood to break at work. I'm actually a Television/radio engineer for a broadcast station. I figure that a programming degree might help me out a lot since everything is controlled by computers now.
Are you planning on getting your degree dude? Seems like it would be cake work for you with the amount you already know. You'd be one of those guys in my class I hate because they've been there, done that. Our first assignment in java 1 was supposed to be really simple and one of the guys used gui interface that was way beyond the scope of the class at the time. I'm not one to hate on anyone, but he certainly made me look bad..hehe
Ok fixed the repeating name problem few more min and ill get the other :) i actually like this program lol
Your onList(String item) method does the 'get a particular item' function. As to the remove item functioning you say you need - that will take some thought - it's not too hard, but it's trickier than the other methods, because you will need to move up all the other items in the array one element after you remove the one item, and reduce the counter.
> Ok fixed the repeating name problem few more min and
> ill get the other :) i actually like this program lol
hehe..really? That makes me feel better. I'm definately a longs way from knowing what I'm doing, but I think that maybe I have a decent sense of design. Maybe someday I'll be an alright programmer :)
> Your onList(String item) method does the 'get a
> particular item' function. As to the remove item
> functioning you say you need - that will take some
> thought - it's not too hard, but it's trickier than
> the other methods, because you will need to move up
> all the other items in the array one element after
> you remove the one item, and reduce the counter.
I figured that was the gist of it, but I'm not sure how to go about doing it. I guess I'll just crack the book and play around a little. Unfortunately we usually just cover theory in class and there aren't that may examples of methods I need. Our teacher made a note of saying that deleting would be a little tricky, but no examples. Guess it's better if I have to use my brain. A few more cans of coffee and I'll be ready :)
import java.util.*;
import newpackage.SquiresMethod;
import javax.swing.*;
public class Main {
public static void main(String[] args)
{
SquiresMethod employeeList = new SquiresMethod();
boolean more1 = true, more2 = true, found = false;
boolean runagain;
String next = "", ans = "", list = "", name = "";
//Creates 4 buttons for the different operations
Object[] options = { "Add new employee ", "Delete employee", "Search for an employee name", "Display employee list" };
do{
int select = JOptionPane.showOptionDialog(null, "What operation do you want to perform", "Choose an option", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
switch (select)
{ case 0:
while ( more1 && (! employeeList.full( )))
{
next = JOptionPane.showInputDialog("Please enter the employee name");
employeeList.addItem(next);
if (employeeList.full( ))
{
JOptionPane.showMessageDialog( null, "The list is full");
}
else
{
employeeList.addItem(next);
ans = JOptionPane.showInputDialog("Would you like to make another entry?");
if (ans.trim( ).equalsIgnoreCase("no"))
more1 = false;
}
}
more1 = true;
break;
case 1:
break;
case 2:
while (more2)
{
String search = JOptionPane.showInputDialog("Please enter the employee name");
found = employeeList.onList(search);
if(found)
JOptionPane.showMessageDialog(null, search + " is in the list");
else
JOptionPane.showMessageDialog(null, search + " is not an employee");
ans = JOptionPane.showInputDialog("Would you like to perform another search?");
if (ans.trim( ).equalsIgnoreCase("no"))
more2 = false;
}
more2 = true;
break;
case 3:
for(int x = 0; x < employeeList.getNumberOfEntries(); x++)
{
name += employeeList.getEntryAt(x) + ", ";
}
JOptionPane.showMessageDialog(null,"The list of employee names is: " + name);
break;
}
select = JOptionPane.showConfirmDialog(null, "Return to main menu?", "Run Again Dialog", JOptionPane.YES_NO_OPTION); //if yes is selected "runagain" equates to true if no is selected "runagain" equates to false
runagain = (select == JOptionPane.YES_OPTION);
} while (runagain); //end of main do-while loop
}
}
import java.util.*;
import javax.swing.*;
public class SquiresMethod
{
public static int START_POSITION = 0;
public static int DEFAULT_SIZE = 10;
//entry.length is the total number of items you have room
//for on the list. countOfEntries is the number of items
//currently on the list.
private int countOfEntries; //our counter -- must be less than entry.length.
private String[] entry;//our array
public SquiresMethod(int maximumNumberOfEntries)// constructor
{
entry = new String[maximumNumberOfEntries];
countOfEntries = 0;
}
/**
Creates an empty list with a capacity of DEFAULT_SIZE.
*/
public SquiresMethod( )// constructor
{
entry = new String[DEFAULT_SIZE];
countOfEntries = 0;
}
public boolean full( )// we use this method in ListDemo
{
return (countOfEntries == entry.length);
}
public boolean empty( )
{
return (countOfEntries == 0);
}
/**
Precondition: List is not full.
Postcondition: If item was not on the list,
it has been added to the list.
*/
public void addItem(String item)
{
if (! onList(item))
{
if (countOfEntries == entry.length)
{
System.out.println("Adding to a full list!");
System.exit(0);
}
else
{
entry[countOfEntries] = item;
countOfEntries++;
}
}//else do nothing. Item is already on the list.
}
/**
If the argument indicates a position on the list,
then the entry at that specified position is returned;
otherwise, null is returned.
*/
public String getEntryAt(int position)// used for printing entire list, for example
{
if (position <= countOfEntries)
return (entry[position]);
else
return " ";
}
/**
Returns true if position is the index of the
last item on the list; otherwise, returns false.
*/
public boolean atLastEntry(int position)
{
return (position == countOfEntries);
}
/**
Returns true if item is on the list;
otherwise, returns false. Does not differentiate
between upper- and lowercase letters.
*/
public boolean onList(String item)// Searches list for item
{
boolean found = false;
int i = 0;
while ((! found) && (i < countOfEntries))
{
if (item.equalsIgnoreCase(entry[i]))
found = true;
else
i++;
}
return found;
}
public int maximumNumberOfEntries( )
{
return entry.length;
}
public int getNumberOfEntries( )
{
return countOfEntries;
}
public void eraseList( )
{
countOfEntries = 0;
}
}
here you go should work
Here's the list of changes i made so you understand:
Main
1) replaced next with name in the for loop so you don't print out the last name you added.
2) added more1 = true; and more2 = true after the while loops also so you can use the functions more than once without having to terminate your program
3) set found = employeeList.onList(search);... before it was employeeList.onList(search) wasn't setting the return value = to anything.
Class
1) set your START_POSITION = 0; to account for index's later;
hope that helps you and i don't know much about java i was only taught Qbasic and SQL but im learning
any duke stars for me? =)
> > Your onList(String item) method does the 'get a
> > particular item' function. As to the remove item
> > functioning you say you need - that will take some
> > thought - it's not too hard, but it's trickier
> than
> > the other methods, because you will need to move
> up
> > all the other items in the array one element after
> > you remove the one item, and reduce the counter.
>
> I figured that was the gist of it, but I'm not sure
> how to go about doing it. I guess I'll just crack the
> book and play around a little. Unfortunately we
> usually just cover theory in class and there aren't
> that may examples of methods I need. Our teacher made
> a note of saying that deleting would be a little
> tricky, but no examples. Guess it's better if I have
> to use my brain. A few more cans of coffee and I'll
> be ready :)
Suppose you had the following array, and a counter:
String[] names = new String[4];
int counter = 0;
Now, suppose you populate three elements:
names[0] = "Berty";
counter++;
names[1] = "Wooster";
counter++;
names[2] = "Jeeves";
counter++;
Now, suppose Berty gets a new butler and fires Jeeves (what a mistake!)
/* ... */
boolean isRemoved = removeName("Jeeves");
/* ... */
boolean removeName(String _name) {
boolean isRemoved = false;
for (int i = 0; i < names.length; i++) {
if ( names[i] != null && _name.equals(names[i]) ) {
isRemoved = true;
names[i] = "";
break;
}
return( isRemoved );
}
This leaves you with a hole in your names array and the count is still unchanged. You can't decrease your count or your will loose access to your uppermost element. So what so you do?
Awesome dude! Thanks so much for all your help. I still have to use a sort method before printing the list and I have to be able to delete an entry, but everything so far is working great now. THANKS!
> Awesome dude! Thanks so much for all your help. I
> still have to use a sort method before printing the
> list and I have to be able to delete an entry, but
> everything so far is working great now. THANKS!
No problem man need anymore help just let me know good luck with it... you got a fun program there... btw i get any duke stars? =)
>>
> Suppose you had the following array, and a counter:
> > String[] names = new String[4];
> int counter = 0;
>
> Now, suppose you populate three elements:
> > names[0] = "Berty";
> counter++;
> names[1] = "Wooster";
> counter++;
> names[2] = "Jeeves";
> counter++;
>
> Now, suppose Berty gets a new butler and fires Jeeves
> (what a mistake!)
> > /* ... */
> boolean isRemoved = removeName("Jeeves");
> /* ... */
> boolean removeName(String _name) {
>boolean isRemoved = false;
> for (int i = 0; i < names.length; i++) {
> if ( names[i] != null && _name.equals(names[i])
> ) {
>isRemoved = true;
> names[i] = "";
>break;
>
>return( isRemoved );
> /code]
> This leaves you with a hole in your names array and
> the count is still unchanged. You can't decrease your
> count or your will loose access to your uppermost
> element. So what so you do?
What about something like this?
Method in Class:
[code]
public String deleteItem(int position ) {
// ensure that the specified position is valid, if not throw an exception
if ( ( 1 > position ) && ( position > countOfEntries ) )
throw new IndexOutOfBoundsException( "Invalid item position: " + position );
// hold a reference to the item being removed
String result = entry[ position - 1 ];
entry[ position - 1 ] = null; // delete our entry
countOfEntries--; // decrease the total entry count by 1
if( countOfEntries > 0 ) // position the cursor at the previous item
position--;
return result; // return the deleted entry to the caller
}
MAIN:
delete =
JOptionPane.showInputDialog("Please enter the employee name you wish to remove:");
employeeList.deleteItem(position);
JOptionPane.showMessageDialog(null, delete + " was removed");
It's not working, but do you think this would work if I had it referenced properly in the main?
Well 1st of all, it does not address the issue that I posited at the end of my previous post ... what do you do to re-compress the array?
2nd of all I don't think you want to do the item search by position because the user is not going to know the position the item is in, and although you could change the method onList to return an int as the position number instead of a boolean, that's not necessarily the best thing because you'd have no way to know what a not-found condition is - remember that 0 is a valid array address.
so your going to store all the names into an array correct? and if so is it going to be in the Main or the Class?
> so your going to store all the names into an array
> correct? and if so is it going to be in the Main or
> the Class?
They're all being stored in the "entry" array in the Class I think, but I'm confusing myself now...too tired...lol
i can tell... here let me see what i can do
> Well 1st of all, it does not address the issue that I
> posited at the end of my previous post ... what do
> you do to re-compress the array?
>
> 2nd of all I don't think you want to do the item
> search by position because the user is not going to
> know the position the item is in, and although you
> could change the method onList to return an int as
> the position number instead of a boolean, that's not
> necessarily the best thing because you'd have no way
> to know what a not-found condition is - remember that
> 0 is a valid array address.
I'm not really sure; can I sort the array or something? To be honest, this is the first assignment where I've use arrays and I found the text to be a little confusing. Sory
> i can tell... here let me see what i can do
Am I wrong; are they not being stored in the entry array? I guess that I don't really understand how that works. I know that when you create an array you designate memory for the elements, but that was one thing I didn't understand from my text. As to exactly how that works. TO be honest, I think I learn better from examples than the theory that they present, but I suppose they can't give you an example for every possible scenario. I really think that if this class was actually taking place in a classroom, I could learn a lot more but online classes suck. Unfortunately, I don't have any other options since I'm in Japan. All I can do is read the text and try to comprehend what they're talking about without the benefit of an instructor.
public boolean deleteItem(String name)
{
int y = 0;
for(int x = 0; x < countOfEntries; x++)
{
if(name == entry[x])
break;
else
{
temp[y] = entry[x];
y++;
}
}
entry = temp;
JOptionPane.showMessageDialog(null, "Name " + name + " has been successfully removed");
return true;
}
Try that.. you will have to make sure you add the temp array at the top i didn't test it though and this will go as another method in your class
Your right they are being stored into array entry[] and i know what you mean array's can be hard. Each array has like a subset of data entry[0] holds one name in your case entry[1] to read a whole array you usualy do a for loop usuing x as a variable or index. not sure if that makes sence. But also if you delete an section of it like entry[1] and there is stuff after it, it doesn't move entry[1] just becomes null;
I tried the method and the program just terminates:
Exception in thread "main" java.lang.NullPointerException
at SquiresMethod.deleteItem(SquiresMethod.java:88)
at SquiresProject3.main(SquiresProject3.java:59)
I'm thinking that the case I put in the main is no good:
case 1:
delete =
JOptionPane.showInputDialog("Please enter the employee name you wish to remove:");
employeeList.deleteItem(name);
break;
No its my fault i forgot to account for something... stand by for fix :)
Ok I'm sorry Im starting to lose it lol here you go
make sure you change these in the class
DEFAULT_SIZE = 0;
private String[] entry = new String[DEFAULT_SIZE];
private String[] temp = new String[DEFAULT_SIZE];
public boolean deleteItem(String name)
{
boolean removed = false;
int y = 0;
for(int x = 0; x < countOfEntries; x++)
{
if(name.equalsIgnoreCase(entry[x]) == false)
{
temp[y] = entry[x];
y++;
}
else
removed = true;
}
countOfEntries = y;
entry = temp;
return removed;
}
Your Main
case 1:
String removeName = JOptionPane.showInputDialog("Enter the name you wish to delete");
if(employeeList.deleteItem(removeName))
JOptionPane.showMessageDialog(null, "Name " + removeName + " was successfuly remove");
else
JOptionPane.showMessageDialog(null, "Sorry the name " + removeName + " is not in the list");
break;
And also add this statement at the end of Case 3 after the JOptionPane but before the break
name = "";
this will allow you to look at your list multiple times and not have the names from before added
Message was edited by:
mark07
Message was edited by:
mark07
You're the man! The last thing I have to do is sort the list when it prints.
I tried using: Arrays.sort(entry, String.CASE_INSENSITIVE_ORDER);
But I'm not sure where it would go; in the method for printing or in the main? I tried putting it in the method but it didn't work. Maybe I had it in the wrong place or there's more to it than just throwing that line in there.
If you don't have time to help that's cool. I might be able to figure this out myself if I get some sleep. You've already been so helpful, I wish I could give you a 1000 duke stars
THANKS!!!!
<The last thing I have to do is sort the list when it ><prints.
in what order? And actually since you have to do all this were probably going to want to change your array's to array lists makes life a whole lot easier>
> <The last thing I have to do is sort the list when it
> <prints.
>
> in what order?
That's a great question...lol. Alphebetically I suppose. Instructor said (traverse and print all records) ...whatever that means. Couldn't find anything more specific so alphebetically should suffice
I gotta go to bed now. Thanks so much for you help man; if you got a chance to help with the sorting than that's cool, but no big deal. I'll talk to you later dude
Take CAre!
> I gotta go to bed now. Thanks so much for you help
> man; if you got a chance to help with the sorting
> than that's cool, but no big deal. I'll talk to you
> later dude
>
> Take CAre!
Check back in about 5 or 6 hours... i have to go to my other job but I'm almost done with it
here ya go this goes into the class
public String[] sort()
{
Arrays.sort(entry, 0, countOfEntries, String.CASE_INSENSITIVE_ORDER);
return entry;
}
and just add this in the main right after case3: and before the for loop
employeeList.sort();
Hope it works out for ya! any other questions just ask
gents,
I got interested... I'm an old c/c++/pascal/basic hack and I haven't done a "popup dialogue" drived app for indigiousPeoples ages.
I renamed, refactored, functionalised, standarised, and generally flocked with everything I could think of to flock with. Here's the result.
package forums;
import javax.swing.JOptionPane;
//##############################################################################
class UnimplementedException extends java.lang.RuntimeException {
private static final long serialVersionUID = 457645612221;
UnimplementedException() {
super();
}
UnimplementedException(String message) {
super(message);
}
}
/**
* EmployeeList class - encapsulates a "list" of employee names.
*/
class EmployeeList {
public static final int DEFAULT_CAPACITY = 10;
private String[] array; // my internal "list" of employees
private int length;// how many employees are there in the list
/**
* default contructor - creates a new EmployeeList of the DEFAULT_CAPACITY (10)
*/
public EmployeeList() {
this(DEFAULT_CAPACITY);
}
/**
* default contructor - creates a new EmployeeList of the specified capacity
*/
public EmployeeList(int capacity) {
this.length = 0;
this.array = new String[capacity];
}
/**
* returns "can the list hold any more employees?"
*/
public boolean isFull() {
return(length >= array.length);
}
/**
* returns "does the list contain any employees?"
*/
public boolean isEmpty() {
return(length==0);
}
/**
* adds the given employee to the list
*/
public void add(String employeeName) throws IndexOutOfBoundsException {
if(length >= array.length) {
throw new IndexOutOfBoundsException("EmployeeList is full.");
}
if(!exists(employeeName)) {
array[length++] = employeeName;
}
}
/**
* returns the employee at the specificed index, or throws an exception
*/
public String item(int index) throws IndexOutOfBoundsException {
if(index<0||index>=this.length) {
throw new IndexOutOfBoundsException("Index "+index+" is not between 0 and "+this.length);
}
return(this.array[index]);
}
/**
* returns "is the specified employee in the list?"
* note: uppercase and lowercase letters are considered equal.
*/
public boolean exists(String employeeName) {
for(int i=0; i<this.length; i++) {
if (array[i].equalsIgnoreCase(employeeName)) {
return(true);
}
}
return(false);
}
/**
* returns "how many employees CAN BE stored in this list?"
*/
public int capacity( ) {
return this.array.length;
}
/**
* returns "how many employees ARE stored in this list?"
*/
public int length( )