Exercise 7

In this exercise, we will work with the following tasks. These tasks together can also be seen as an example of a possible exam.

Task 5 uses the class JTextField which we have not talked about. You should not expect that such an class will be on the real exam, but by reading the task and the code it is still not difficult to understand how the program works. Note especially how the actionPerformed in TextListener is executed when the user typed a new letter followed by ↵.

     
  1. Consider the following program:
    public class Task1 {
    
         public static void p(int n, Counter c) {
             n = c.getValue();
             c = new Counter();
         }
    
         public static void main(String [] args) {
             Counter c = new Counter();
             int n = 0;
             c.incr();
             p(n, c);
             System.out.println(n + "" + c.getValue ());
         }
    }
    

    The program uses the class Counter, that we discussed several times; For reasons of space, we do not repeat it here.

    What does the program print when it is run? Explain briefly.

  2. We say that a sequence of integers a0, a1, ... an-1 is growing if a0 < a1 < ... < an-1. (If n = 1 the sequence is growing independently of a0 and if n = 0, then the sequence is empty and is then also growing by definition.) Define a class Task2 with two methods:
    public static boolean increasing(int [] a);
    public static void main(String [] args);
    
    The first of these determines whether the numbers in the argument array represent a growing sequence. The other is a single main method testing the first method by command line arguments stored in a field of integers, the increasing method is called with this array of arguments and the result of the call will be printed. Example use:
    > java Task2 3 5 82 93
    true
    > java Task2 3 5 82 2 45 67
    false
    > java Task2 4
    true
    
  3. Write a simple class BankAccount to represent bank accounts with the following methods:

    Accounts are created with zero balances. Unlike from real banks, all transactions are in integer values.

  4. The same banking application that requires the previous class also contains class
    import java.util. *;
    
    public class Customer {
      private Person name;
      private List<BankAccount> accounts;
      ...
      public int totalBalance() {...}
      ...
    }
    
    Several methods and state variables are skipped; it suffices to see that the instance variables include a list of bank accounts.

    Define the method totalBalance, which returns the total balance for all the customer's accounts.  

  5. We consider the game "Hangman", where the user should attempt to guess a secret word. From the beginning, you know just how many letters the word contains, as in the image below:   

         

    The word thus has 13 letters. Then the user guesses a letter at a time; the letters included in the word are filled in the correct location(s); otherwise commence hang. The user makes their guesses with the keyboard; they appear in the text field at the bottom. Above is the secret word programmering. The user guessed S, A, t, r, i, k, n and b which resulted in the following situation:   

         

    Four letters were right and four were wrong, which led to drawing four parts of the gallows and the hanging man. If the user continues in this way the end state can become:   

         

    After nine incorrect guesses, the man is hanged and the player has lost.

    The program, which is given below, consists (as usual) of four classes:

     

      Two things are included in the given program:  

         
    1. The program selects the secret word by reading a file with words and chooses a random word among them. The file name is given on the command line. If the file is called words then the program is run with:
      > java Main words
      
       

      We do not know how many words are in the file, but it is enough to choose among no more than the first 1000 words. The secret is chosen in function chooseSecret in Main. Define this function.    

    2. class HangManModel keeps the secret, the partial solution and the number of errors. Among other things, it has the method:
      public void guess(char c)
      
      that is called when the user has made a guess. The method should fill in the guesses made in the right places and it should note when the guess was incorrect. Define the method.
     
  6. We want to write a Java program to build and compute simple electrical circuits. We start with resistors; a class whose objects are resistors must implement the interface:
    public interface Resistor {
         public double getResistance ();
         public int nrOfComponents ();
    }
    

    The first method returns the total resistance value, the second the number of simple resistor components in the total circuit.

    We can create resistors in three different ways:   

    Your task is now:  
        
    1. Define the class ParallelResistor.   
    2. Type a main routine that tests your class by building a resistor by parallel connection of 100 simple resistors with resistance 1, 2, ..., 100 ohms and prints both the total resistance and the number of simple resistors.   

  Below is the code to the task 5th  
public class HangManModel {

    private String secret;
    private char [] word; // partial solution
    private int errors; // nr of errors

    public HangManModel(String secret) {
	this.secret = secret;
	word = new char [secret.length()];
        for (int i=0; i< word.length; i++)
            word[i] = '-';
    }

    public void guess(char c) {
       // left to define
    }

    public String showWord() {
        // create a String from an array of chars
	return new String(word);
    }

    public int getErrorCount() {
	return errors;
    }
}

import java.awt.*; import javax.swing.*; public class HangManPanel extends JPanel { private static final int WIDTH = 600; private static final int HEIGHT = 200; private HangManModel model; private Font bigFont,smallFont; public HangManPanel(HangManModel model) { this.model = model; bigFont = new Font("Monospaced",Font.PLAIN,36); smallFont = new Font("Monospaced",Font.BOLD,20); setPreferredSize(new Dimension(WIDTH,HEIGHT)); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); g.setFont(smallFont); g.drawString("Gissa det hemliga ordet:",200,80); g.setFont(bigFont); g.drawString(model.showWord(),200,140); paintHangMan(g,model.getErrorCount()); } private void paintHangMan(Graphics g,int err) { if (err > 0) g.drawLine(20,50,20,190); if (err > 1) g.drawLine(20,50,100,50); if (err > 2) g.drawLine(100,50,100,70); if (err > 3) g.drawOval(90,70,20,20); if (err > 4) g.drawLine(100,90,100,140); if (err > 5) g.drawLine(100,100,70,110); if (err > 6) g.drawLine(100,100,130,110); if (err > 7) g.drawLine(100,140,80,180); if (err > 8) { g.drawLine(100,140,120,180); g.setColor(Color.red); g.setFont(bigFont); g.drawString("Beklagar!",200,180); } } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HangManView extends JPanel { private HangManModel model; private JTextField guessField; private HangManPanel panel; public HangManView(HangManModel model) { this.model = model; panel = new HangManPanel(model); guessField = new JTextField(25); setLayout(new BorderLayout()); add(panel,BorderLayout.CENTER); add(guessField,BorderLayout.SOUTH); guessField.addActionListener(new TextListener()); } private class TextListener implements ActionListener { public void actionPerformed(ActionEvent e) { String g = guessField.getText(); model.guess(g.charAt(g.length()-1)); repaint(); } } }
import java.io.*; import java.util.*; import javax.swing.*; public class Main { public static String chooseSecret(String file) throws IOException { // left to define } public static void main(String [] args) throws IOException { String secret = chooseSecret(args[0]); HangManModel model = new HangManModel(secret); HangManView view = new HangManView(model); JFrame f = new JFrame("Hangman"); f.add(view); f.pack(); f.setVisible(true); } }