So I've been working on this project PhoneBook.java program for awhile. The program opens up a .txt file and imports it into a List sorted by Lastname, Firstname. I am attempting to write a search function that opens a window, asks you to input a name, then upon clicking ok it should select the searched index. I can not understand why my following code for the searchMI is not working. I appreciate any help you can give me.
public class PhoneBook extends Frame implements ActionListener, ItemListener {
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem searchMI, deleteMI, updateMI, newEntryMI, sortMI;
String fileName;
List nameList;
List numberList;
TextField lastName, firstName, phoneNumber;
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI)
{
nameList.removeAll();
numberList.removeAll();
fileName = null;
display(-1);
setTitle("White Pages")
}
else if(source == searchMI)
{
String searchName = JOptionPane.showInputDialog(this,
"Please enter a name (last first) to search:");
System.out.println("Name to search: " + searchName);
int index = nameList.getSelectedIndex();
String name = lastName.getText().trim() + " " + firstName.getText().trim();
for(int i=0; i!=index; i++){
if(nameList.equals(searchName)){
nameList.select(index);
}
else
{
System.out.println("Error searching for the name: " + searchName);
}
...
Suggestions
Why this: int index = nameList.getSelectedIndex();? It does not look as if the selected index will give you any useful information here.
This will never work: if(nameList.equals(searchName)){. A List cannot equal a String.
Instead use your for loop, loop through whatever collection holds the Strings, I'm guessing it's the nameList and compare the String held at each item with the entered String.
The for loop should go from i = 0 to i < nameList.getItemCount() (or nameList.size() if it is a java.util.List).
Don't have that else block, else{ System.out.println("Error searching for the name: "... inside of the for loop. Doing that will print out the else Statement many times.
You're better off using the Swing library components not AWT.
You'll want to format your posted code better. Each statement should have its own line. Careful and regular indentations matter.
Since you are using components in your GUI, you may not need that JOptionPane. Could you instead get the search String from one of your text fields?
Related
Basically i want to enter the names as long as i don't cancel the InputMessageDialog, then i want to asign my names to variable created before and print them out at the end in the MessageDialog. I was trying some stuff outside the loop but got the notificacion that "value 'names' is always 'null'"
String names;
while (true) {
names = JOptionPane.showInputDialog(null, "ENTER THE NAMES");
if (names == null) {
JOptionPane.showMessageDialog(null, "ENTRY CANCELED!");
break;
} else {
}
}
JOptionPane.showMessageDialog(null, "YOUR NAMES: " + names);
Your code is pretty close to what you describe as your goal – the primary thing missing is that you need to keep track of the various values along the way, and print them at the end.
The code you posted will loop again and again asking for a single value (which you are storing into String names - a little confusing choice for variable name, since it contains only one name input). As you found, when the user hits the cancel button (to end the loop), it sets names to null. The final step shows a dialog box with the last value for names (which is always null).
Here's a program that:
loops until the user hits the "cancel" button (which would set input to be null), or if they enter a blank value – this allows the user to exit by simply hitting return without typing anything
adds all non-empty input values to a java.util.Set – this is an arbitrary choice, use whatever data structure is appropriate for your program
shows a final dialog with the contents of the set
import javax.swing.*;
import java.util.HashSet;
import java.util.Set;
public class t {
public static void main(String[] args) {
Set<String> values = new HashSet<>();
while (true) {
String input = JOptionPane.showInputDialog(null, "enter something");
if (input != null && !input.isEmpty()) {
values.add(input);
} else {
break;
}
}
JOptionPane.showMessageDialog(null, "all values: " + values);
}
}
If I run with the following input:
one
two two
three three three
<blank>
Then the final dialog message is:
all values: [one, two two, three three three]
Note that a java.util.Set doesn't necessarily return items in any specific order, it just happens to have worked out that way in this example.
I am trying to make a game, at the start, the first part is fine, however, I cannot get the second question working, I would like it to display: rules_yes if Yes is entered (case insensitive), and rules_no to be displayed if anything else is written. At the moment, no matter what I input for the rules, it only runs the rules_yes. Can I get some feed back on how to make this work?
{
String user_name;
String name_answer;
String yes_no;
String rules_yes;
String rules_no;
char input;
private char yes;
private char Yes;
{
user_name = JOptionPane.showInputDialog("Enter Your Name");
name_answer = ("Hello " + user_name + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog( null, name_answer );
}
{
yes_no = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
if (input == Yes || input == yes)
{
rules_yes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rules_yes );
}
else
{
rules_no = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rules_no );
}
}
You have many issues with your code, and many things you can do to simplify it.
yes and Yes are not initialized, this caused your program to fail.
You can declare yes_no as a String, then use if (yes_no.equalsIgnoreCase("y");(rather than using char yes and char Yes)
This does not affect your program, but you have a lot of spacing between lines, which makes it seem like a lot more than it is.
input is unnecessary, so you can just delete it.
So your final code can look like this:
import javax.swing.JOptionPane;
public class ScratchPaper {
public static void main(String[]args) {
String userName;
String nameAnswer;
String rulesYes;
String rulesNo;
String yesNo;
userName = JOptionPane.showInputDialog("Enter Your Name");
nameAnswer = ("Hello " + userName + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog( null, nameAnswer );
yesNo = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
if (yesNo.equalsIgnoreCase("y"))
{
rulesYes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rulesYes );
}
else {
rulesNo = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rulesNo );
}
}
}
If you have any questions, please comment below, and I will answer them as soon as I can. Thank you!
Because you adding (Y/N) question value to "yes_no" param, but your 'if-else' condition working with 'input' so the input not initialized thats mean it's equals to 0.That's why your question always returning YES.
Change your code like this :
public static void main(String[] args) {
String user_name;
String name_answer;
String yes_no;
String rules_yes;
String rules_no;
char[] input;
char Yes = 0;
{
user_name = JOptionPane.showInputDialog("Enter Your Name");
name_answer = ("Hello " + user_name + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog(null, name_answer);
}
{
yes_no = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
input = yes_no.toCharArray();
if (input[0] == Yes) {
rules_yes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog(null, rules_yes);
} else {
rules_no = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog(null, rules_no);
}
}
}
Why are you using an "input" dialog?
An easier solution would be to just use a "message" dialog with "Yes", "No" buttons for the user to click on.
Read the section from the Swing tutorial on How to Make Dialogs for more information and examples.
In this program, I am getting incorrect output for the ArrayList.
In the first line, it always prints every single element of the ArrayList horizontally.
It then will correctly print the ArrayList.
Can someone take a look at the code and see if I did something wrong? I will show you the two classes.
Class 1:
public class contactDriver
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println ("What would you like to do?");
int answer;
System.out.println ("Press 1 to add a contact.");
System.out.println ("Press 2 to display all contacts.");
answer = scan.nextInt();
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("Patrick McGee", "334-555-8860", "pmcgee123#gmail.com"));
contacts.add(new Contact("John Appleseed", "142-555-6740", "jappleseed99#gmail.com"));
contacts.add(new Contact("Matt Jordan", "213-555-2323", "mjordan23#gmail.com"));
contacts.add(new Contact("Kanye East", "255-434-9909", "keast123#gmail.com"));
contacts.add(new Contact("Derrick Flower", "144-555-1111", "dflower1#gmail.com"));
if (answer == 1){
System.out.println ("Please enter the first and last name of the contact.");
String name = scan.next();
scan.nextLine();
System.out.println ("Please enter the phone number of the contact.");
String num = scan.next();
scan.nextLine();
System.out.println ("Please enter the email of the contact.");
String email = scan.next();
scan.nextLine();
contacts.add(new Contact(name, num, email));
}
if (answer == 2){
}
System.out.println(contacts);
for(Contact c : contacts) {
System.out.println(c);
Class 2:
public class Contact
{
public Contact(String name, String num, String email)
{
this.name = name;
this.num = num;
this.email = email;
}
public String getFirstname()
{
return name;
}
public String getNum()
{
return num;
}
public String getEmail()
{
return email;
}
public String toString()
{
return "Contact[" + name + ", " + num + ", " + email + "]";
}
private String name;
private String num;
private String email;
}
The output:
[Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com], Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com], Contact[Matt Jordan, 213-555-2323, mjordan23#gmail.com], Contact[Kanye East, 255-434-9909, keast123#gmail.com], Contact[Derrick Flower, 144-555-1111, dflower1#gmail.com]
(all in one line).
Then prints:
Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com]
Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com]
... so on.
Any ideas on the fix?
Thanks :)
The output
[Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com], Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com], Contact[Matt Jordan, 213-555-2323, mjordan23#gmail.com], Contact[Kanye East, 255-434-9909, keast123#gmail.com], Contact[Derrick Flower, 144-555-1111, dflower1#gmail.com]
is due to
System.out.println(contacts);
This prints a String representation (by the method toString()) of the ArrayList contacts.
Edit
To don't get this output just delete that line. The for you are using to print each Contact looks fine:
for(Contact c : contacts) {
System.out.println(c);
}
You've an extra sysout statement which is printing the extra values. System.out.println(contacts); prints all the elements of the array list(All contacts in one line).
[Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com], Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com], Contact[Matt Jordan, 213-555-2323, mjordan23#gmail.com], Contact[Kanye East, 255-434-9909, keast123#gmail.com], Contact[Derrick Flower, 144-555-1111, dflower1#gmail.com]
I guess you just wanted to print the plain text "contacts" and then print each and every contact, like this.
if (answer == 2){
System.out.println("contacts:"); // prints the plain text contacts
for(Contact c : contacts) {
System.out.println(c); // prints each contact using the toString() implementation provided by you
}
}
And if you do not want to print any text before printing each contact in the list, then just remove the extra sysout statement.
if (answer == 2){
// System.out.println(contacts); // not needed - commented/deleted
for(Contact c : contacts) {
System.out.println(c); // prints each contact using the toString() implementation provided by you
}
}
I don't really understand what the problem is. I'm not sure if the issue is it printing horizontally in one line (although it seems you have figured out how to get it to print on multiple lines), or if that the problem is that it is printing twice, once on one line and once on multiple.
I'm going to try and explain why it does what it does, maybe that will help you. If you can clarify what the issue is I'm sure I could help if this doesn't answer your question.
So, I'm not sure if this was intentional or not, but the if statement at the bottom of your first class has nothing inside its code block. It has no purpose unless you put code inside of it, if you don't plan on doing that, you could go ahead and remove it.
if (answer == 2){
}
System.out.println(contacts);
for(Contact c : contacts) {
System.out.println(c);
As you can see, the curly brace underneath it is stopping any of that code from being inside executed by the if statement. All of that code will be ran with the program regardless of whether or not the 1 or 2 was inputted. If you wish for some of that code underneath (or all) to be ran when number 2 is inputted, put it inside those curly braces. Otherwise you can leave it out and it will run regardless of the option selected.
There are two things happening at the end of the first class.
System.out.println(contacts);
This is telling it to print the entire arraylist in one line. That is why you get the horizontal line of all contacts.
for(Contact c: contacts){
System.out.println(c);
}
This is telling it to loop through the arraylist and print each individual contact on its own separate line. That is why you get the 2nd output. Please note that in your original post you were missing a curly brace after the bottom for loop, I added it in this post.
I hope that clears up any confusion. You should be able to choose if you want both of those outputs, or if you want one or both to run only when option 2 is selected. Again, I wasn't really sure what the issue was, so I tried to just give an overview of what the code was doing. I apologize that this post was so lengthy. Clearly the other people answering did a better job of using less text. Good luck on your code!
I need to write a program that will have a user enter a list of tutor names. Only up to 10 peer tutors may be hired. Then, the program will present each name, based on a list alphabetized by last name. This is what I have so far, but it does not work and I don't know what to do. I need it to continue to run until I stop it and continue with more of the program.
import javax.swing.JOptionPane;
import java.util.Arrays;
public class Report {
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames();
}
public static String[] getTutorNames() {
String firstName;
String lastName;
String[] listNames = new String[10];
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals("")) && lastName.equals("")) {
break; // loop end
}
listNames[x] = lastName + ", " + firstName;
}
return listNames;
}
}
Well, this is a first. IntelliJ didn't format the code correctly when I edited it, and I soon discovered this hit-list of errors. Just bear in mind - the code won't even compile, let alone run, until these are fixed.
int numTutors comes out of nowhere. If you want to define it, then do so outside of the method call and set it to an appropriate value.
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames(numTutors);
}
These declarations are invalid:
String = firstName;
String = lastName;
You need some sort of variable name in between String and =.
You're also not matching the contract for what you're passing in to getTutorNames - either what you pass in or what you accept must change. I'm thinking that it's the latter.
You can't use == to compare String. You have to use .equals(). Which leads me to...
Your break is outside of your loop. Move it inside of the loop.
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals(" "))&&lastName.equals(" ")){
break; // loop end
}
}
..and that leads me to...
You don't put the values anywhere through the loop! You're just running the same code ten times! Place them into the array.
// after you check to see if the firstName and lastName are blank
listNames[x] = firstName + lastName; // I don't know what you want to do with them from here.
There is no .add() for an array. The above is how you enter elements into an array.
Your return is outside of your method block entirely. Move it into your method.
Now, these are the issues that I could find. Work on the compilation issues first, then one may talk about errors in code logic. If you can, snag a quiet moment and ensure you understand variable declaration and String comparison. I would strongly recommend the reading material found in the Java wiki tag.
So sorry for making an answer for something this small but your
If (firstName.equals("")) && lastName.equals("")) {
Should be replaced by
If ((firstName.equals("")) && lastName.equals(""))) {
I have a String named updatedDisplay that is set to empty in the constructor.
The buttons[] are JButtons and alarmCode is a String field.
I want the user to press four buttons (and they should be concatenated and stored in the updatedDisplay field).
The checkCode() method is executed to try match updatedDisplay against alarmCode. Trouble is, they never match. I think it may be something to do with a "space" when I originally declare my updatedDisplay as follows:
private String updatedDisplay = " ";
The updatedDisplay field doesn't seem to be storing the e.getActionCommand() value.
//add actionListeners to each button (except the "clear" button) to display value on screen
for (int i = 0; i< (buttons.length -1); i++) {
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//store the name of the button in a local variable
String command = e.getActionCommand();
System.out.println("You clicked " + command);
updatedDisplay = updatedDisplay + command;
//updatedDisplay = command;
System.out.println (updatedDisplay);
screen.setText(updatedDisplay);
}
});}
I have an armButton that, when pressed, should trigger the checkCode() method. The method checks if updatedDisplay and alarmCode are equal:
//add actionListener to the arm button
armButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
checkCode();
}
});
checkCode():
public void checkCode() {
//check if user entered the correct code
if (updatedDisplay == alarmCode)
{
updatedDisplay = "System Armed!";
screen.setText(updatedDisplay);
}
else
{
updatedDisplay = "Incorrect Code, Try again!";
screen.setText(updatedDisplay);
}
}
Even when I output the button presses to the terminal window they look right - but as I said, I suspect a "space" is being entered at the start.
Any ideas?
Solution
Try:
if( updatedDisplay.equals( alarmCode ) { // ...
Comparison
To understand this, read:
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Summary
Since updatedDate and alarmCode are object references, you must ask the objects to compare their values. You can think of them as pointers whose values are locations in memory that contain strings. Rather than comparing the value of the pointers (references), you want to compare the text that starts at that memory location.