gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:59:19 25 4
gpt4 key购买 nike

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

我认为问题出在代码的最后部分,我将字符串的第一个字母和最后一个字母与数组进行比较。但我不确定。我花了一些时间研究,但我被困住了。

欢迎任何意见。你不会伤害我的感情。

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

}

}

最佳答案

因为您只需要一个字符,所以应该使用 charAt() 而不是 substring。虽然 substring 是可能的,但我总是忘记哪个参数是包含的或排除的。我想你也会的。

您应该声明 2 个字符:

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

然后你可以检查它们:

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

关于java - 从Java中的字符串数组中提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33850115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com