用java代码写一个背单词程序
时间: 2023-08-25 09:06:06 浏览: 87
好的,下面是一个简单的Java代码示例,实现一个背单词程序的基本功能:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class Vocabulary {
private ArrayList<String> words;
private ArrayList<String> meanings;
private int currentIndex;
public Vocabulary() {
words = new ArrayList<String>();
meanings = new ArrayList<String>();
currentIndex = 0;
}
public void addWord(String word, String meaning) {
words.add(word);
meanings.add(meaning);
}
public void startQuiz() {
Scanner scanner = new Scanner(System.in);
String input;
System.out.println("Welcome to vocabulary quiz!");
while (currentIndex < words.size()) {
System.out.println("What is the meaning of \"" + words.get(currentIndex) + "\"?");
input = scanner.nextLine();
if (input.equalsIgnoreCase(meanings.get(currentIndex))) {
System.out.println("Correct!");
currentIndex++;
} else {
System.out.println("Incorrect! The correct answer is \"" + meanings.get(currentIndex) + "\".");
}
}
System.out.println("Congratulations! You have finished the quiz.");
}
public static void main(String[] args) {
Vocabulary vocabulary = new Vocabulary();
vocabulary.addWord("apple", "a round fruit with red or green skin");
vocabulary.addWord("banana", "a long yellow fruit with soft flesh");
vocabulary.addWord("cherry", "a small round fruit with a red or black skin");
vocabulary.startQuiz();
}
}
```
上述代码定义了一个`Vocabulary`类,其中包含了一个单词列表和一个意思列表。通过调用`addWord`方法,可以向单词列表和意思列表中添加新的单词和意思。
`startQuiz`方法是整个程序的核心功能,它会逐个呈现单词,让用户输入对应的意思。如果用户输入的意思和正确答案一致,程序会提示“Correct!”并进入下一个单词。如果用户输入的意思和正确答案不一致,程序会提示“Incorrect!”并显示正确答案。
在`main`方法中,我们创建了一个`Vocabulary`对象,并添加了一些单词和意思。最后,调用`startQuiz`方法开始背单词。
阅读全文