0

I'm making a game where the user enters his/her first name and last name. The program extracts the first letters from the names, then outputs names from a string array.

I'm thinking the issue is in the last part of the code, where I'm comparing the Strings firstletter and lastLetter to the array. But I'm not sure. I have spent some time researching, and I'm stuck.

Any comments welcome. You won't hurt my feelings.

import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner; 

public abstract class ChristmasName extends JFrame implements ActionListener {


public static void main(String[] args) {

    JFrame frame = new JFrame("What is your Christmas Name?");
    frame.setVisible(true);
    frame.setSize(400,300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    frame.add(panel);

    JLabel firstName = new JLabel("First name:");
        JTextField first = new JTextField(15);
    JLabel lastName = new JLabel("Last name:");
        JTextField last = new JTextField(15);
    panel.add(firstName);
    panel.add(first);
    panel.add(lastName);
    panel.add(last);

    JButton submit = new JButton("Submit");
    panel.add(submit);
    submit.addActionListener(new ActionListener() {

        @Override
        public actionPerformed(ActionEvent e) {
           String[] first_name = {"Apple","Eggnogg","Candy","Jingle","Holly","Goldie","Ho Ho","Frosty","Joyous","Mittens","Tinsel","Turkey","Tiny","Cranberry","Bloated","Angel","Bauble","Bulb","Ginger","Blitzen","Eve","Faith","Fruitcake","Goose","Glitter","Grinch"};
           String[] last_name = {"Tidings","Swan","Jolly","Claus","Mistletoe","Punch","Chimney","Coal","Igloo","Jumper","Myrhh","Pudding","Reindeer","Rejoice","Icicle","Midnight","Shepherd","Surprise","Gift","Magi","Train","Tree","White","Donkey","Wreath","Stuffing"};

           String firstLetter = first.getText();
           firstLetter = firstLetter.substring(0,1);

           String lastLetter = last.getText();
           lastLetter = lastLetter.substring(0,1);

           if (firstLetter == "A") {
               firstLetter = first_name[0];

           }



           JOptionPane.showMessageDialog(null, firstLetter + " " + lastLetter);
           System.exit(0);     
        }
    });    

}

}

JennyJ
  • 13
  • 6
  • What exactly is wrong? What inputs are you providing, what is the output, and what is the expected output? – DBug Nov 22 '15 at 00:06
  • Either use `char` or compare strings properly. – PM 77-1 Nov 22 '15 at 00:06
  • 1
    Compare String with equals() not == – dragon66 Nov 22 '15 at 00:06
  • can you update your question to say what exactly is the expected output and what is wrong with the output you actually get? – EkcenierK Nov 22 '15 at 00:06
  • When testing equality of strings in Java, you should use the equals method, e.g., `firstLetter.equals("A") or firstLetter.equalsIgnoreCase("A")`. – johnnieb Nov 22 '15 at 02:33
  • the firstLetter.equals() solution worked great. This isn't a very elegant program, but I'm trying to teach myself how to manipulate array items. – JennyJ Nov 22 '15 at 23:38

4 Answers4

1

Not sure what you're asking but the first problem I see in your code is:

if (firstLetter == "A") { firstLetter = first_name[0];

}

See the following on how to check if two strings have the same value: How do I compare strings in Java?

Community
  • 1
  • 1
1

Because you only need one character, you should use charAt() instead of substring. Although substring is possible, I always forget which parameter is inclusive or exclusive. I think you will too.

You should declare 2 chars:

char firstChar = first.getText().charAt(0);
char lastChar = last.getText ().charAt (0);

And then you can check them:

if (firstChar == 'A') { //Remember to use single quotes!
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

Here's my solution for your problem:

String[] first_names = {"Apple","Eggnogg","Candy","Jingle","Holly","Goldie","Ho Ho","Frosty","Joyous","Mittens","Tinsel","Turkey","Tiny","Cranberry","Bloated","Angel","Bauble","Bulb","Ginger","Blitzen","Eve","Faith","Fruitcake","Goose","Glitter","Grinch"};
String[] last_names = {"Tidings","Swan","Jolly","Claus","Mistletoe","Punch","Chimney","Coal","Igloo","Jumper","Myrhh","Pudding","Reindeer","Rejoice","Icicle","Midnight","Shepherd","Surprise","Gift","Magi","Train","Tree","White","Donkey","Wreath","Stuffing"};

// User Input:
// Note: converted to lower case so the chars can be compared easily.
String firstName = first.getText().toLowerCase();
String lastName = last.getText().toLowerCase();

// Vars for output:
String sChristmasFirstName = null;
String sChristmasLastName = null;

// Do first name (if entered)
if(firstName.length() > 0){
    // Loop all names to find the match:
    for(String name : first_names){
        if(name.toLower().charAt(0) == firstName.charAt(0)){
            // We found a Christmas first name for the user
            sChristmasFirstName = name;
            // we can now exit the loop
            break;
        }

    }
} // else, the user left this field blank

// Do same thing for last name
if(firstName.length() > 0){
    // Loop all names to find the match:
    for(String name : last_names){
        if(name.toLower().charAt(0) == lastName.charAt(0)){
            // We found a Christmas last name for the user
            sChristmasLastName = name;
            // we can now exit the loop
            break;
        }

    }
} // else, the user left this field blank

// Prepare output string:
String output = "";
String outputErrorPortion = "";
if(sChristmasFirstName != null){
    output += sChristmasFirstName;
}else{
    if(firstName.length() == 0){
        outputErrorPortion += "It looks like you didn't enter a first name.";
    }else{
        // Could not find an applicable first name
        output += firstName;
        ouputErrorPortion += "It looks like we couldn't find a Christmas first name for you :-(";
    }
}

if(sChristmasLastName != null){
    output += " " + sChristmasLastName;
}else{
    if(lastName.length() == 0){
        outputErrorPortion += " It looks like you didn't enter a last name.";
    }else{
        // Could not find an applicable last name
        output += " " + lastName;
        ouputErrorPortion += " It looks like we couldn't find a Christmas last name for you :-(";
    }
}

// trim leading and trailing spaces if there are any:
output = output.trim();
outputErrorPortion = outputErrorPortion.trim();

// Variable 'output' now contains the Christmas first name, last name, both, or neither.
// Error message now contains a descriptive error about what happened (if anything)

The string comparisons to choose the Christmas names occurs in a for each loop which loops over the first_names and last_names String arrays to find the first match that starts with the same letter as the user's inputted first and last names. The Christmas names are then concatenated at the end to the output variable with the user's inputted first and/or last names being used in place of the Christmas equivalent if a relevant entry could not be found in the arrays of Christmas names. An error message is also constructed in the outputErrorPortion variable if any errors occurred while processing to names.

Spencer D
  • 3,376
  • 2
  • 27
  • 43
0

Here is the code you need read it carefully:

            String[] firstNames = { "Apple", "Eggnogg", "Candy", "Jingle", "Holly", "Goldie", "Ho Ho", "Frosty","Joyous", "Mittens", "Tinsel", "Turkey", "Tiny", "Cranberry", "Bloated", "Angel", "Bauble","Bulb", "Ginger", "Blitzen", "Eve", "Faith", "Fruitcake", "Goose", "Glitter", "Grinch" };
            String[] lastNames = { "Tidings", "Swan", "Jolly", "Claus", "Mistletoe", "Punch", "Chimney", "Coal","Igloo", "Jumper", "Myrhh", "Pudding", "Reindeer", "Rejoice", "Icicle", "Midnight", "Shepherd","Surprise", "Gift", "Magi", "Train", "Tree", "White", "Donkey", "Wreath", "Stuffing" };

            // ArrayLists will contain the matching items
            ArrayList<String> firstNamesMatching = new ArrayList<String>();
            ArrayList<String> lastNamesMatching = new ArrayList<String>();

            // Check which names from firstNames matching the firstLetter
            String firstLetter = first.getText().substring(0, 1).toUpperCase();
            for (String s : firstNames) {
                if (s.startsWith(firstLetter))
                    firstNamesMatching.add(s);
            }

            // Check which names from lastNames matching the lastLetter
            String lastLetter = last.getText().substring(0, 1).toUpperCase();
            for (String s : lastNames) {
                if (s.startsWith(lastLetter))
                    lastNamesMatching.add(s);
            }

            JOptionPane.showMessageDialog(null, firstNamesMatching.toArray() + " " + lastNamesMatching);

Also:

Although the arrays firstNames and lastNames and etc have to be outside the actionListener.You should have in mind the memory that your program use and not initialize the same things again and again.

GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
  • Thank you. I think I'll try this one first. – JennyJ Nov 22 '15 at 20:23
  • This is really cool code, so thank you, because I'm sure I'll be able to use this at some point. I don't think it's the right one for this project. For example, if someone entered "Allysa" as their first name, wouldn't the app always assign "Apple" as the Christmas name, and never get to Angel? – JennyJ Nov 22 '15 at 23:33
  • (Sorry, hit "enter" too soon.) I could change all the names in the array to start with different letters, and then your code would work beautifully. But, I was trying to learn how to compare items, then output items in the arrays based on their positions. – JennyJ Nov 22 '15 at 23:35
  • @JennyJ about your second comment.The ArrayList(array-list)has all the possible names starting from the first letter.For example with letter A it contains Apple and Angel.If now from them you want to extract one lexicographical(for example) then you can add some more code... – GOXR3PLUS Nov 23 '15 at 02:22