// if .. else if .. else, equalIgnoreCase, random, Dialogs
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Translator extends Frame implements ActionListener
{
public static void main(String[] args)
{
new Translator();
}
JOptionPane io = new JOptionPane(); // use io for Input and Message Dialogs
TextField word = new TextField("Type a word here");
Button trans = new Button("Translate to German");
Button quiz = new Button("Quiz about numbers");
Button quit = new Button("Exit Program");
public Translator()
{
setSize(150,150);
setLayout(new FlowLayout());
add(word);
add(trans);
add(quiz);
add(quit);
word.addActionListener(this);
trans.addActionListener(this);
quiz.addActionListener(this);
quit.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
String english = word.getText(); // get English word from TextField
String german; // use this to store the answer
if (source == trans || source == word)
{
if ( english.equalsIgnoreCase("hello") )
{ german = "Guten Tag"; }
else if (english.equalsIgnoreCase("money"))
{ german = "Geld"; }
else if (english.equalsIgnoreCase("food"))
{ german = "Essen"; }
else if (english.equalsIgnoreCase("happy"))
{ german = "froh"; }
else if (english.equalsIgnoreCase("work"))
{ german = "Arbeit"; }
else if (english.equalsIgnoreCase("book"))
{ german = "Buch"; }
else
{ german = "unknown - try Google"; }
io.showMessageDialog(this,german); // display the answer
}
else if (source == quiz)
{
int q = (int)(Math.random()*4) + 1; // random number 1,2,3,4
String guess = io.showInputDialog(this,
"How do you say this number in German? " + q);
// ask the question
String answer = "";
if (q == 1)
{
if (guess.equals("eins")) { answer = "Correct!"; }
else { answer = "No, the correct word is : eins"; }
}
if (q == 2)
{
if (guess.equals("zwei")) { answer = "Right!"; }
else { answer = "No, the correct word is : zwei"; }
}
if (q == 3)
{
if (guess.equals("drei")) { answer = "Good!"; }
else { answer = "No, the correct word is : drei"; }
}
if (q == 4)
{
if (guess.equals("vier")) { answer = "Outstanding!"; }
else { answer = "No, the correct word is : vier"; }
}
io.showMessageDialog(this,answer);
}
else if (source == quit)
{ System.exit(0);}
}
}
|