CSCI 1101 – Winter 2012
Laboratory No. 5
SOLUTIONS
Exercise 1: A teacher has five students who have taken a test. The teacher uses the following grading scale to assign a letter grade to a student, based on the test score:
Test scoreLetter grade
90.0-100A
80.0-89.9B
70.0-79.9C
60.0-69.9D
0-59.9F
Write a class called Grades that has the following attributes:
- String array to hold the five students’ names
- an array of five characters to hold the five students’ letter grades,
- and an array of five doubles to hold the five test scores
and the following methods:
- No-args constructor (Note: the arrays are created in the declarations).
- Method setName(String, int) that puts the name in the name array at a given index.
- Method getName(int) that returns the name from the name array from a given index
- Method setScore(double, int) that puts the test score in the scores array at a given index
- Method getScore(int) that returns the score from the scores array from a given index
- Method findGrade(int) that determines the grade given an index and puts it in the grades array.
- Method getGrade(int) that returns the grade from the grades array from a given index.
Demonstrate the class in a program that allows the user to enter each student’s name and his or her test score. It should then display each student’s name, average test score and letter grade.
SOLUTION:
//Grades.java
public class Grades
{
private String[] name = new String[5];
private char[] grade = new char[5];
private double[] score = new double[5];
public Grades()
{
}
public void setName(String n, int i)
{
name[i] = n;
}
public String getName(int i)
{
return name[i];
}
public void setScore(double val, int i)
{
score[i] = val;
}
public double getScore(int i)
{
return score[i];
}
public void findGrade(int i)
{
if (score[i] >=90.0)
grade[i] = 'A';
else if (score[i] >=80.0)
grade[i] = 'B';
else if (score[i] >= 70.0)
grade[i] = 'C';
else if (score[i] >= 60.0)
grade[i] = 'D';
else
grade[i] = 'F';
}
public char getGrade(int i)
{
return grade[i];
}
}
//GradesDemo.java
import java.util.Scanner;
public class GradesDemo
{
public static void main(String[] args)
{
Grades myClass = new Grades();
Scanner keyboard = new Scanner(System.in);
String name;
double val;
System.out.println("Enter five names: ");
for(int i = 0; i< 5; i++)
{
name = keyboard.next();
myClass.setName(name,i);
}
System.out.println("Enter five scores: ");
for(int i = 0; i< 5; i++)
{
val = keyboard.nextDouble();
myClass.setScore(val, i);
myClass.findGrade(i);
}
for(int i =0; i<5; i++)
{
System.out.print(myClass.getName(i) + "\t" + myClass.getScore(i) + "\t" + myClass.getGrade(i) + "\n");
}
}
}
Exercise 2: Write a Lottery class that simulates a lottery. The class has the following attributes:
- lotteryNumbers: array of five integers
- userArray: array of five integers
- matches: number of matches
and the following methods:
- Constructor: takes in no arguments. It should use the Random class to generate five random numbers in the range of 1 through 9 and puts them in the lotteryNumbers array
- Method that accepts an array of five integers that represent a person’s lottery picks.
- Method should compare the corresponding elements in the two arrays and finds the number of matches. For example, the following shows the lotteryNumbers array and the user array with sample numbers stored in each. There are two matching digits (numbers 9 and 3). Note that the digits should be in the same position as well.
lotteryNumbers array:
74913
user array:
42973
- Method printPrize that prints the lotteryNumbers array, the user array and the prize. The prize is determined according to the following rules:
Grand Prize ($1 million):all five digits match
$500,000 prize:four out of five match
$1000 prize:three out of five match
$10 prize:two out of five match
$2 prize:one out of five match
Demonstrate the class in a program that asks the user to enter five numbers. The program should display the lotteryNumbers array and the user’s array and the number of digits that match. It should also display a message about the prize.
SOLUTION:
//Lottery.java
public class Lottery
{
private int[] lotteryNumbers = new int[5];
private int[] userArray = new int[5];
private int matches=0;
public Lottery()
{
int num;
for(int i=0; i<5; i++)
{
num = (int)(Math.random()*9+1);
lotteryNumbers[i] = num;
}
}
public void getUserPicks(int[] a)
{
for(int i=0; i<5; i++)
userArray[i] = a[i];
}
public void findMatches()
{
for(int i=0; i<5; i++)
{
if (lotteryNumbers[i] == userArray[i])
matches++;
}
}
public void printPrize()
{
for(int i = 0; i<5; i++)
System.out.print(lotteryNumbers[i] + "\t");
System.out.println();
for(int i = 0; i<5; i++)
System.out.print(userArray[i] + "\t");
System.out.println();
if (matches==5)
System.out.println("Grand Prize: 1 Million!!");
else if (matches == 4)
System.out.println("Prize: $500,000");
else if (matches == 3)
System.out.println("Prize: $1000");
else if (matches == 2)
System.out.println("Prize: $10");
else
System.out.println("Sorry. No luck");
}
}
//LotteryDemo.java
import java.util.Scanner;
public class LotteryDemo
{
public static void main(String[] args)
{
Lottery myLottery = new Lottery();
int num;
int[] picks = new int[5];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your pick (five numbers from 1 to 9): ");
for(int i = 0; i< 5; i++)
{
num = keyboard.nextInt();
picks[i] = num;
}
myLottery.getUserPicks(picks);
myLottery.getMatches();
myLottery.printPrize();
}
}
Exercise 3: Write a program that randomly fills in 0s and 1s into an 8 X 8 checker board, prints the board, and finds the rows, columns, or diagonal with all 0s or 1s. Use a 2-d array to represent the checker board. Here is a sample run of the program:
10101000
10100001
11100011
10100001
11100111
10000001
10100111
00100001
Check: All 0’s on subdiagonal.
public class Lab2Ex2 {
public static void main(String[] args) {
int[][] board = new int[8][8];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
board[i][j] = (int) (Math.random() * 2);
System.out.print(board[i][j]);
}
System.out.println();
}
// Check rows
for (int i = 0; i < board.length; i++) {
boolean same = true;
for (int j = 1; j < board[0].length; j++) {
if (board[i][0] != board[i][j]) {
same = false;
break;
}
}
if (same)
System.out.println("All " + board[i][0] + "'s on row " + i);
}
// Check columns
for (int j = 0; j < board[0].length; j++) {
boolean same = true;
for (int i = 1; i < board.length; i++) {
if (board[0][j] != board[i][j]) {
same = false;
break;
}
}
if (same)
System.out.println("All " + board[0][j] + "'s on column " + j);
}
// Check major diagonal
boolean same = true;
for (int i = 1; i < board.length; i++) {
if (board[0][0] == board[i][i]) {
same = false;
break;
}
}
if (same)
System.out.println("All " + board[0][0] + "'s on major diagonal");
// Check subdiagonal
same = true;
for (int i = 1; i < board.length; i++) {
if (board[0][7] == board[i][7 - i]) {
same = false;
break;
}
}
if (same)
System.out.println("All " + board[0][0] + "'s on subdiagonal");
}
}
Bonus Challenge: Write a method to multiply two matrices. The header of the method is as follows:
public static int [][] multiplyMatrix(int[][] a, int [][] b)
To multiply matrix a by matrix b, the number of columns in a must be the same as the number of rows in b. Let c be the result of the multiplication, and a, b, and c are denoted as follows:
a11 a12 a13b11 b12 b13c11 c12 c13
a21 a22 a23Xb21 b22 b23=c21 c22 c23
a31 a32 a33 b31 b32 b33c31 c32 c33
where cij = ai1Xb1j + ai2Xb2j + ai3Xb3j
Test your method in a main program.
import java.util.Scanner;
public class Matrix {
/** Main method */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int N = 3;
// Enter matrix1
System.out.print("Enter matrix1: ");
double[][] matrix1 = new double[N][N];
for (int i = 0; i < matrix1.length; i++)
for (int j = 0; j < matrix1[i].length; j++) {
matrix1[i][j] = input.nextDouble();
}
// Enter matrix2
System.out.print("Enter matrix2: ");
double[][] matrix2 = new double[N][N];
for (int i = 0; i < matrix1.length; i++)
for (int j = 0; j < matrix1[i].length; j++) {
matrix2[i][j] = input.nextDouble();
}
// Multiply two matrices and print the result
double[][] resultMatrix = multiplyMatrix(matrix1, matrix2);
System.out.println("\nThe multiplication of the matrices is ");
printResult(matrix1, matrix2, resultMatrix, '*');
}
/** The method for multiplying two matrices */
public static double[][] multiplyMatrix(
double[][] m1, double[][] m2) {
double[][] result = new double[m1.length][m2[0].length];
for (int i = 0; i < m1.length; i++)
for (int j = 0; j < result.length; j++)
for (int k = 0; k < result[0].length; k++)
result[i][j] += m1[i][k] * m2[k][j];
return result;
}
/** Print result */
public static void printResult(
double[][] m1, double[][] m2, double[][] m3, char op) {
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++)
System.out.print(" " + m1[i][j]);
if (i == m1.length / 2)
System.out.print( " " + op + " " );
else
System.out.print( " " );
for (int j = 0; j < m2[0].length; j++)
System.out.print(" " + m2[i][j]);
if (i == m1.length / 2)
System.out.print( " = " );
else
System.out.print( " " );
for (int j = 0; j < m3[0].length; j++)
System.out.print(" " + m3[i][j]);
System.out.println();
}
}
}