Create a separate class file for each problem, and email all files as attachments to me at jal2016@email.vccs.edu with subject CSC 201 HW4.
Alternately, you can create a Mercurial repository named 201-hw
and put your
homework in a hw4
folder within the repository. See
this post from the 185 section for details.
Due Thursday, Feb 9.
1
Write a program that allows the user to type in a list of numbers and then prints all the numbers in order from smallest to largest.
Use an ArrayList<Double>
object to keep track of all the numbers.
The java.util.Collections
class has a bunch of utilities that
are useful for processing collections (including ArrayList
s),
analogous to those used for plain arrays in java.util.Arrays
.
The sort
method will be useful here.
Here's a template that includes the imports I'd suggest:
import java.util.Collections;
import java.util.ArrayList;
import java.util.Scanner;
public class NumberSort {
public static void main(String[] args) {
// Create an object to store all numbers.
// Set up a loop to read numbers.
// You'll have to decide how to tell when you're done.
// Sort the numbers.
// Print the sorted numbers.
}
}
2
Write a program that lets two players play tic-tac-toe. Here's a start you can use if you want:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
public class TicTacToe extends JPanel {
// Represent gameboard using a bunch of buttons
JButton[][] buttons;
public TicTacToe() {
// Set layout and size to reasonable values
setLayout(new GridLayout(3,3));
setPreferredSize(new Dimension(500, 500));
// Create a font object to use with the buttons
Font font = new Font("Sans", Font.BOLD, 100);
// Initialize buttons
buttons = new JButton[3][3];
for (int row = 0; row < buttons.length; row++)
for (int col = 0; col < buttons[row].length; col++) {
JButton b = new JButton("");
b.setFont(font);
buttons[row][col] = b;
add(b);
// Add action listeners here?
}
}
// Set up main window and add our components.
public static void buildGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new TicTacToe());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
buildGUI();
}
});
}
}
One way to check for a winner is as follows: after each move, if there is a winner it will have to be using either the row, the column, or the diagonal where the move was placed. Check all three of those after each move.