我对以下问题有疑问。
现在,在下面的问题 1 中,它想要创建一个 java 类。
- 创建一个名为 Words 的 Java 类,其中包含以下内容:
import javax.swing.JOptionPane;
public class Words {
public static void main(String[] args) {
WordList ws = new WordList();
String in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
while (in != null) {
ws.addWord(in);
in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
}
JOptionPane.showMessageDialog(null, "Word list = " +
ws.toString());
JOptionPane.showMessageDialog(null, "First word = " +
ws.getFirst());
JOptionPane.showMessageDialog(null, "Last word = " +
ws.getLast());
}
}
在问题 2 中,它提出以下问题:
在现有的 Practical1 项目中创建一个名为 WordList 的 Java 类,其中包含以下内容:
在 Words 类的源代码窗口中右键单击并选择“运行文件”。输入几个单词,每个单词后单击“确定”,然后观察程序的行为。
确保您了解该应用程序的工作原理。在 WordList 类中,按照相关注释的描述修改 getFirs 和 getLast 方法。相关注释位于下面的 WordList.java 类中:
import java.util.ArrayList;
public class WordList {
private ArrayList<String> theWordList = new ArrayList<String>();
public void addWord(String s) {
theWordList.add(s);
}
public String getFirst() {
// Replace the return statement below with a statement
// that returns
// the first word of theWordList (the word at index 0).
// Hint: use the ArrayList method "get".
// If there is no first word (theWordList has no words in it),
* "-" should be returned.
//
return "junk";
}
public String getLast() {
// Replace the string "junk" with the
// last word of theWordList (the word
// at index size()-1). Hint: use the ArrayList method "get".
// If there is no last word (theWordList has no words in it),
// "-" should be returned.
//
return "junk";
}
public String toString() {
return theWordList.toString();
}
}
我更困惑的主要问题是他们在完成问题 4 的步骤中给我留下的评论。我该如何在这里回答这些问题?
如果您需要另一个类(即主类),这里是它及其标签为 Words.java:
import javax.swing.JOptionPane;
public class Words {
public static void main(String[] args) {
WordList ws = new WordList();
String in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
while (in != null) {
ws.addWord(in);
in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
}
JOptionPane.showMessageDialog(null, "Word list = " +
ws.toString());
JOptionPane.showMessageDialog(null, "First word = " +
ws.getFirst());
JOptionPane.showMessageDialog(null, "Last word = " +
ws.getLast());
}
}
最佳答案
如何从ArrayList中获取内容
对于 public String getFirst() {
if (theWordList.isEmpty ()) {
return "-";
return theWordList.get (0); // first element of List
对于 public String getLast() {
执行与上面相同的空检查,然后返回
使用theWordList.size () -1
关于java - 构建单词列表处理应用程序的初始版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60843385/