从Java中的字符串数组中提取

时间:2015-11-22 00:01:53

标签: java arrays string

我正在制作一个用户输入他/她的名字和姓氏的游戏。程序从名称中提取第一个字母,然后从字符串数组中输出名称。

我认为这个问题出现在代码的最后部分,我将Strings firstletter和lastLetter与数组进行比较。但我不确定。我花了一些时间研究,而且我被卡住了。

欢迎任何评论。你不会伤害我的感情。

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);     
        }
    });    

}

}

4 个答案:

答案 0 :(得分:1)

不确定您要问的是什么,但我在您的代码中看到的第一个问题是:

  

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

     

}

请参阅以下有关如何检查两个字符串是否具有相同值的信息: How do I compare strings in Java?

答案 1 :(得分:1)

因为您只需要一个字符,所以应使用charAt()代替substring。虽然substring是可能的,但我总是忘记哪个参数是包含性的还是排他性的。我想你也一样。

你应该声明2个字符:

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

然后你可以查看它们:

if (firstChar == 'A') { //Remember to use single quotes!

答案 2 :(得分:1)

这是我解决问题的方法:

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)

用于选择圣诞节名称的字符串比较发生在每个循环中,循环遍历first_nameslast_names字符串数组以查找以与用户相同的字母开头的第一个匹配&#39 ;输入名字和姓氏。然后圣诞节名称最后连接到output变量,如果在阵列中找不到相关条目,则用户输入的第一个和/或最后一个名称代替圣诞节等价物圣诞节的名字。如果在处理名称时发生任何错误,则outputErrorPortion变量中也会构造错误消息。

答案 3 :(得分:0)

以下是您需要仔细阅读的代码:

            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);
  

此外:

虽然数组firstNames和lastNames等必须在actionListener之外。你应该记住程序使用的内存,而不是一次又一次地初始化相同的内容。