Tic Tac Toe Game
VerifiedAdded on  2019/09/21
|26
|6874
|98
Report
AI Summary
The assignment is to create a Tic-Tac-Toe game in Java, where players input their moves and the program determines if there is a winner or if the game has ended in a draw. The game should allow for multiple games to be played without terminating until explicitly requested.
Contribute Materials
Your contribution can guide someone’s learning journey. Share your
documents today.
Fraction Problem
Create a class called Fraction. Provide a constructor that takes 2 integers. Provide methods for
ď‚· toString
ď‚· setFraction
ď‚· equals
ď‚· add
ď‚· subtract
ď‚· multiple
ď‚· divide
ď‚· reduce - make sure you get the previous methods done before worrying about reduce.
The following will be your starting point:
package fractions;
import java.util.*;
public class Fraction
{
private Scanner scan = new Scanner(System.in);
private int num=1;
private int denom=1;
public Fraction()
{
}
public Fraction(int n, int d)
{
// Fill in code (good to use setFraction)
}
public void setFraction(int n, int d)
{
//Fill in code ... don't forget to reduce
}
public Fraction add(Fraction op)
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b + c/d = (a*d + b*c)/(b*d)
}
public Fraction subtract(Fraction op)
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b - c/d = (a*d - b*c)/(b*d)
}
Create a class called Fraction. Provide a constructor that takes 2 integers. Provide methods for
ď‚· toString
ď‚· setFraction
ď‚· equals
ď‚· add
ď‚· subtract
ď‚· multiple
ď‚· divide
ď‚· reduce - make sure you get the previous methods done before worrying about reduce.
The following will be your starting point:
package fractions;
import java.util.*;
public class Fraction
{
private Scanner scan = new Scanner(System.in);
private int num=1;
private int denom=1;
public Fraction()
{
}
public Fraction(int n, int d)
{
// Fill in code (good to use setFraction)
}
public void setFraction(int n, int d)
{
//Fill in code ... don't forget to reduce
}
public Fraction add(Fraction op)
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b + c/d = (a*d + b*c)/(b*d)
}
public Fraction subtract(Fraction op)
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b - c/d = (a*d - b*c)/(b*d)
}
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
public Fraction multiply(Fraction op)
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b * c/d = (a*c)/ (b*d)
}
public Fraction divide(Fraction op)
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b / c/d = (a*d)/ (b*c)
}
private void reduce()
{
// Pseudo code:
// set smaller = minimum ( abs(num), abs(denom));
// Loop through the possible divisors: 2, 3, 4, ... smaller
// For each possible divisor:
// while (num and denom are evenly divisible by divisor)
// {
// num /= divisor;
// denom /= divisor;
// smaller /= divisor;
// }
}
public boolean equals(Fraction f)
{
// Assuming all fractions are reduced
// Fill in code
}
public String toString()
{
// Fill in code
}
public void readin(String label)
{
while (true) // Keep trying if bad input is received
{
System.out.print(label);
String temp = scan.next();
temp = temp.trim(); // get rid of white space at the beginning and
end
int index = temp.indexOf('/');
if (index >= 0)
{
String numStr = temp.substring(0, index);
String denomStr = temp.substring(index+1);
int n = Integer.parseInt(numStr);
int d = Integer.parseInt(denomStr);
setFraction(n,d);
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b * c/d = (a*c)/ (b*d)
}
public Fraction divide(Fraction op)
{
//Fill in code ... don't forget to reduce
// Algebra HINT: a/b / c/d = (a*d)/ (b*c)
}
private void reduce()
{
// Pseudo code:
// set smaller = minimum ( abs(num), abs(denom));
// Loop through the possible divisors: 2, 3, 4, ... smaller
// For each possible divisor:
// while (num and denom are evenly divisible by divisor)
// {
// num /= divisor;
// denom /= divisor;
// smaller /= divisor;
// }
}
public boolean equals(Fraction f)
{
// Assuming all fractions are reduced
// Fill in code
}
public String toString()
{
// Fill in code
}
public void readin(String label)
{
while (true) // Keep trying if bad input is received
{
System.out.print(label);
String temp = scan.next();
temp = temp.trim(); // get rid of white space at the beginning and
end
int index = temp.indexOf('/');
if (index >= 0)
{
String numStr = temp.substring(0, index);
String denomStr = temp.substring(index+1);
int n = Integer.parseInt(numStr);
int d = Integer.parseInt(denomStr);
setFraction(n,d);
return;
}
else
System.out.println("Input Fraction missing / ");
}//Keep trying until you get it right
}
public static void main(String[] args)
{
Fraction f1= new Fraction();
Fraction f2= new Fraction();
Fraction f3=null;
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.println(); // Add a blank line
System.out.print("Enter operation: + - * / q (q ==> quit) : ");
String input = scan.next();
if (input.charAt(0) == 'q')
break; // All done
f1.readin("Enter Fraction 1: ");
f2.readin("Enter Fraction 2: ");
System.out.println("f1 = " + f1);
System.out.println("f2 = " + f2);
if (f1.equals(f2))
System.out.println("f1 and f2 are equal");
else
System.out.println("f1 and f2 are not equal");
switch (input.charAt(0))
{
case '+':
f3 = f1.add(f2);
System.out.println("f1+f2=" + f3);
break;
case '-':
f3 = f1.subtract(f2);
System.out.println("f1-f2=" + f3);
break;
case '*':
f3 = f1.multiply(f2);
System.out.println("f1*f2="+f3);
break;
case '/':
f3 = f1.divide(f2);
System.out.println("f1/f2="+f3);
break;
default:
}
else
System.out.println("Input Fraction missing / ");
}//Keep trying until you get it right
}
public static void main(String[] args)
{
Fraction f1= new Fraction();
Fraction f2= new Fraction();
Fraction f3=null;
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.println(); // Add a blank line
System.out.print("Enter operation: + - * / q (q ==> quit) : ");
String input = scan.next();
if (input.charAt(0) == 'q')
break; // All done
f1.readin("Enter Fraction 1: ");
f2.readin("Enter Fraction 2: ");
System.out.println("f1 = " + f1);
System.out.println("f2 = " + f2);
if (f1.equals(f2))
System.out.println("f1 and f2 are equal");
else
System.out.println("f1 and f2 are not equal");
switch (input.charAt(0))
{
case '+':
f3 = f1.add(f2);
System.out.println("f1+f2=" + f3);
break;
case '-':
f3 = f1.subtract(f2);
System.out.println("f1-f2=" + f3);
break;
case '*':
f3 = f1.multiply(f2);
System.out.println("f1*f2="+f3);
break;
case '/':
f3 = f1.divide(f2);
System.out.println("f1/f2="+f3);
break;
default:
System.out.println("Illegal command: " + input );
break;
}
}// end of while loop
System.out.println("Bye");
} // end of main
}
Please try to run the following Fraction calculations:
(note the answers are filled with ______)
Enter operation: + - * / q (q ==> quit) : +
Enter Fraction 1: 1/3
Enter Fraction 2: 4/6
f1 = 1/3
f2 = 2/3
f1 and f2 are not equal
f1+f2=_________
Enter operation: + - * / q (q ==> quit) : +
Enter Fraction 1: 5/25
Enter Fraction 2: 10/50
f1 = 1/5
f2 = 1/5
f1 and f2 are equal
f1+f2=_________
Enter operation: + - * / q (q ==> quit) : +
Enter Fraction 1: 7/30
Enter Fraction 2: 11/20
f1 = 7/30
f2 = 11/20
f1 and f2 are not equal
f1+f2=_________
Enter operation: + - * / q (q ==> quit) : -
Enter Fraction 1: 11/12
Enter Fraction 2: 4/5
f1 = 11/12
f2 = 4/5
f1 and f2 are not equal
f1-f2=_________
Enter operation: + - * / q (q ==> quit) : *
Enter Fraction 1: 5/6
Enter Fraction 2: 1/4
f1 = 5/6
f2 = 1/4
break;
}
}// end of while loop
System.out.println("Bye");
} // end of main
}
Please try to run the following Fraction calculations:
(note the answers are filled with ______)
Enter operation: + - * / q (q ==> quit) : +
Enter Fraction 1: 1/3
Enter Fraction 2: 4/6
f1 = 1/3
f2 = 2/3
f1 and f2 are not equal
f1+f2=_________
Enter operation: + - * / q (q ==> quit) : +
Enter Fraction 1: 5/25
Enter Fraction 2: 10/50
f1 = 1/5
f2 = 1/5
f1 and f2 are equal
f1+f2=_________
Enter operation: + - * / q (q ==> quit) : +
Enter Fraction 1: 7/30
Enter Fraction 2: 11/20
f1 = 7/30
f2 = 11/20
f1 and f2 are not equal
f1+f2=_________
Enter operation: + - * / q (q ==> quit) : -
Enter Fraction 1: 11/12
Enter Fraction 2: 4/5
f1 = 11/12
f2 = 4/5
f1 and f2 are not equal
f1-f2=_________
Enter operation: + - * / q (q ==> quit) : *
Enter Fraction 1: 5/6
Enter Fraction 2: 1/4
f1 = 5/6
f2 = 1/4
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
f1 and f2 are not equal
f1*f2=_________
Enter operation: + - * / q (q ==> quit) : /
Enter Fraction 1: 6/7
Enter Fraction 2: 1/12
f1 = 6/7
f2 = 1/12
f1 and f2 are not equal
f1/f2=_________
Enter operation: + - * / q (q ==> quit) : q
Bye
string_array
Create a package named string_array and write a program that creates an array of Strings with
the name of "firstNames".
Fill the array with the names(in this order): "George", "Fred", "Sam", "Mary", "Sarah", "Bella",
"Joy", "Rita", "Marta", "Sue", "Nancy"
Print the values of the firstNames array backwards. In otherwords, your output should be:
Nancy Sue Marta Rita Joy Bella Sarah Mary Sam Fred George
Run the program and insert the results in the appropriate section of the JH5 worksheet.
date_array
Create a package named date_array and you will need 2 classes. Create a class called MyDate.
This class only needs the following things:
ď‚· Instance variables for month, day and year
f1*f2=_________
Enter operation: + - * / q (q ==> quit) : /
Enter Fraction 1: 6/7
Enter Fraction 2: 1/12
f1 = 6/7
f2 = 1/12
f1 and f2 are not equal
f1/f2=_________
Enter operation: + - * / q (q ==> quit) : q
Bye
string_array
Create a package named string_array and write a program that creates an array of Strings with
the name of "firstNames".
Fill the array with the names(in this order): "George", "Fred", "Sam", "Mary", "Sarah", "Bella",
"Joy", "Rita", "Marta", "Sue", "Nancy"
Print the values of the firstNames array backwards. In otherwords, your output should be:
Nancy Sue Marta Rita Joy Bella Sarah Mary Sam Fred George
Run the program and insert the results in the appropriate section of the JH5 worksheet.
date_array
Create a package named date_array and you will need 2 classes. Create a class called MyDate.
This class only needs the following things:
ď‚· Instance variables for month, day and year
ď‚· Constructor: MyDate(String month, int day, int year) - the code stores the values in 3
instance variables
ď‚· String toString() method - returns a String containing your 3 instance variables.
Create another class called DateArray that creates an array of "MyDate" with the name of
"dateArr".
The array should have 4 entries and the entries should be filled with MyDate classes representing
the dates:
May 16, 1984
November 14, 1978
September 21, 1980
July 3, 1987
The DateArray class should print the values of the dateArr array backwards. Your MyDate
classes can be printed using a toString() method in the MyDate class.
Run the program and insert the results in the appropriate section of the JH5 worksheet.
one_dimensional_array problem (15 points):
Create a package named one_dimensional_array and write a class that completes the following
"OneDimensionalArrays" class. You will complete the class by filling in code wherever you see
the comment:
//******* FILL IN CODE *********
import java.util.Scanner;
public class OneDimensionalArrays {
int[] createIntegers(int size_of_array)
{
//******* FILL IN CODE *********
// Your code will create an array of ints as large as specified in
size_of_array
// Fill the array in with the values: 0, 100, 200, 300, ....
// Return the array that you just created
}
void printArray(int[] myArray)
{
instance variables
ď‚· String toString() method - returns a String containing your 3 instance variables.
Create another class called DateArray that creates an array of "MyDate" with the name of
"dateArr".
The array should have 4 entries and the entries should be filled with MyDate classes representing
the dates:
May 16, 1984
November 14, 1978
September 21, 1980
July 3, 1987
The DateArray class should print the values of the dateArr array backwards. Your MyDate
classes can be printed using a toString() method in the MyDate class.
Run the program and insert the results in the appropriate section of the JH5 worksheet.
one_dimensional_array problem (15 points):
Create a package named one_dimensional_array and write a class that completes the following
"OneDimensionalArrays" class. You will complete the class by filling in code wherever you see
the comment:
//******* FILL IN CODE *********
import java.util.Scanner;
public class OneDimensionalArrays {
int[] createIntegers(int size_of_array)
{
//******* FILL IN CODE *********
// Your code will create an array of ints as large as specified in
size_of_array
// Fill the array in with the values: 0, 100, 200, 300, ....
// Return the array that you just created
}
void printArray(int[] myArray)
{
//******* FILL IN CODE *********
// Print out your array with one number per line. Get the size of the
// array from the "myArray" parameter (no hard coding the size)
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter size of array to create: ");
int num = keyboard.nextInt();
//******* FILL IN CODE *********
// Construct an instance of the OneDimensionalArrays class
// Using this object instance, call createIntegers to create
// an array of integers. Don't forget to save the results
// Then call the printArray method to print out the contents
// of your array.
}
}
Run your program and insert the results in the appropriate section of the JH5 worksheet.
// Print out your array with one number per line. Get the size of the
// array from the "myArray" parameter (no hard coding the size)
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter size of array to create: ");
int num = keyboard.nextInt();
//******* FILL IN CODE *********
// Construct an instance of the OneDimensionalArrays class
// Using this object instance, call createIntegers to create
// an array of integers. Don't forget to save the results
// Then call the printArray method to print out the contents
// of your array.
}
}
Run your program and insert the results in the appropriate section of the JH5 worksheet.
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Fantasy Football Problem
This exercise is very similar to the GradeBook.java example near the end of
Chapter 6
of your textbook. Make sure you have watched the video "GradeBook and Fantasy
Football" found
in the " Arrays Part2" section. The Textbook's GradeBook example does many of
the same things
that you will need to do in your Fantasy Football program.
However, instead of a teacher grade book, we have the following
fantasy football scores:
Create a FantasyFootball.java class to read in the information in the above
table.
One of the differences in the overall structure is the fact that in Gradebook
we didn't have any
Student names. In Fantasy Football we want a name for each team. This will
require adding an
additional array to store the names of the teams. You will simplify your
efforts if the names of your
teams do not include spaces. Then you can use next() instead of nextLine()
and your code will be simplified.
You will get most of the credit for this assignment even if your output is not
completely
aligned as shown in the above image. Note that if you use the technique from
GradeBook.java
you will get a ragged looking table.
Getting the table aligned as seen in the above image will give you the last 5
points on this
problem.
You can get the alignment to look somewhat OK, if you use tab characters to go
to new columns
and round the double values to integer values with a cast operation.
This exercise is very similar to the GradeBook.java example near the end of
Chapter 6
of your textbook. Make sure you have watched the video "GradeBook and Fantasy
Football" found
in the " Arrays Part2" section. The Textbook's GradeBook example does many of
the same things
that you will need to do in your Fantasy Football program.
However, instead of a teacher grade book, we have the following
fantasy football scores:
Create a FantasyFootball.java class to read in the information in the above
table.
One of the differences in the overall structure is the fact that in Gradebook
we didn't have any
Student names. In Fantasy Football we want a name for each team. This will
require adding an
additional array to store the names of the teams. You will simplify your
efforts if the names of your
teams do not include spaces. Then you can use next() instead of nextLine()
and your code will be simplified.
You will get most of the credit for this assignment even if your output is not
completely
aligned as shown in the above image. Note that if you use the technique from
GradeBook.java
you will get a ragged looking table.
Getting the table aligned as seen in the above image will give you the last 5
points on this
problem.
You can get the alignment to look somewhat OK, if you use tab characters to go
to new columns
and round the double values to integer values with a cast operation.
However, you can get perfect alignment using the System.printf(....) approach
we have shown before.
Consider the following examples of printf and println:
String s ="something";
double d = 5.4321;
int x = 3456;
System.out.printf("%20s", s); //Field of 20 characters, right justified
string
System.out.printf("%-20s", s); //Field of 20 characters, left justified
string
System.out.printf("%8d", x); //Field of 8 characters, right justified
integer
System.out.prinf("%-8d", x); //Field of 8 characters, left justified
integer
System.out.println(); // Go to a new line
You should start with the "Starting Code" shown below.
Starting Code
package fantasy_football;
import java.util.Scanner;
public class FantasyFootball
{
private int numberOfTeams; // Same as teamAverage.length.
private int numberOfWeeks; // Same as weekAverage.length.
private int[][] scores; //numberOfTeams rows and numberOfWeeks columns.
private double[] weekAverage; // contains an entry for each week
private double[] teamAverage; // contains an entry for each team
private String[] teamName; // contains an entry for each team
public void enterInData( )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of teams:");
numberOfTeams = keyboard.nextInt( );
System.out.println("Enter number of weeks:");
numberOfWeeks = keyboard.nextInt( );
// ************** Fill in Code ***************
// Allocate array memory for teamName to store the team names.
// Allocate array memory for scores (2 dimensional array) to store a
// score for each team for each week.
we have shown before.
Consider the following examples of printf and println:
String s ="something";
double d = 5.4321;
int x = 3456;
System.out.printf("%20s", s); //Field of 20 characters, right justified
string
System.out.printf("%-20s", s); //Field of 20 characters, left justified
string
System.out.printf("%8d", x); //Field of 8 characters, right justified
integer
System.out.prinf("%-8d", x); //Field of 8 characters, left justified
integer
System.out.println(); // Go to a new line
You should start with the "Starting Code" shown below.
Starting Code
package fantasy_football;
import java.util.Scanner;
public class FantasyFootball
{
private int numberOfTeams; // Same as teamAverage.length.
private int numberOfWeeks; // Same as weekAverage.length.
private int[][] scores; //numberOfTeams rows and numberOfWeeks columns.
private double[] weekAverage; // contains an entry for each week
private double[] teamAverage; // contains an entry for each team
private String[] teamName; // contains an entry for each team
public void enterInData( )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of teams:");
numberOfTeams = keyboard.nextInt( );
System.out.println("Enter number of weeks:");
numberOfWeeks = keyboard.nextInt( );
// ************** Fill in Code ***************
// Allocate array memory for teamName to store the team names.
// Allocate array memory for scores (2 dimensional array) to store a
// score for each team for each week.
for (int team = 0; team < numberOfTeams; team++)
{
System.out.println("Enter team name");
// ************* Fill in Code **************
// Read in Team name and store it in teamName
for (int week = 0; week < numberOfWeeks; week++)
{
System.out.println("Enter score for team "+ teamName[team]);
System.out.println("on week number " + (week+1));
// ************ Fill in Code ***************
// Read in a score and store it in the proper spot in the
scores array
}
}
}
public void fillTeamAverage( )
{
//********* Fill in Code *************
// Allocate memory for the teamAverage.
// Each entry in this array will contain the
// average weekly score for a given team.
}
public void fillWeekAverage( )
{
//*********** Fill in Code *************
// Allocate memory for the weekAverage instance variable.
// Each entry in this array will contain the average of
// all teams for a given week.
}
public void display( )
{
//********* Fill in Code ****************
// This method will print out the display that was shown above.
// At this point all of the information can be found in the
// private instance variables of the FantasyFootball class
}
public static void main(String[] args)
{
FantasyFootball f= new FantasyFootball();
f.enterInData();
f.fillTeamAverage();
f.fillWeekAverage();
{
System.out.println("Enter team name");
// ************* Fill in Code **************
// Read in Team name and store it in teamName
for (int week = 0; week < numberOfWeeks; week++)
{
System.out.println("Enter score for team "+ teamName[team]);
System.out.println("on week number " + (week+1));
// ************ Fill in Code ***************
// Read in a score and store it in the proper spot in the
scores array
}
}
}
public void fillTeamAverage( )
{
//********* Fill in Code *************
// Allocate memory for the teamAverage.
// Each entry in this array will contain the
// average weekly score for a given team.
}
public void fillWeekAverage( )
{
//*********** Fill in Code *************
// Allocate memory for the weekAverage instance variable.
// Each entry in this array will contain the average of
// all teams for a given week.
}
public void display( )
{
//********* Fill in Code ****************
// This method will print out the display that was shown above.
// At this point all of the information can be found in the
// private instance variables of the FantasyFootball class
}
public static void main(String[] args)
{
FantasyFootball f= new FantasyFootball();
f.enterInData();
f.fillTeamAverage();
f.fillWeekAverage();
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
f.display();
}
}
************************************
Sample Output from your program:
Enter number of teams:
4
Enter number of weeks:
3
Enter team name
Blind_Pigeons
Enter score for team Blind_Pigeons
on week number 1
123
Enter score for team Blind_Pigeons
on week number 2
95
Enter score for team Blind_Pigeons
on week number 3
121
Enter team name
Spittn_Lamas
Enter score for team Spittn_Lamas
on week number 1
54
Enter score for team Spittn_Lamas
on week number 2
98
Enter score for team Spittn_Lamas
on week number 3
83
Enter team name
Nut_Zippers
Enter score for team Nut_Zippers
on week number 1
70
Enter score for team Nut_Zippers
on week number 2
74
Enter score for team Nut_Zippers
on week number 3
103
Enter team name
Bucking_Broncos
Enter score for team Bucking_Broncos
on week number 1
108
Enter score for team Bucking_Broncos
on week number 2
119
Enter score for team Bucking_Broncos
on week number 3
81
********************************
output from display() with ragged output
********************************
Blind_Pigeons 123 95 121 Ave = 113
}
}
************************************
Sample Output from your program:
Enter number of teams:
4
Enter number of weeks:
3
Enter team name
Blind_Pigeons
Enter score for team Blind_Pigeons
on week number 1
123
Enter score for team Blind_Pigeons
on week number 2
95
Enter score for team Blind_Pigeons
on week number 3
121
Enter team name
Spittn_Lamas
Enter score for team Spittn_Lamas
on week number 1
54
Enter score for team Spittn_Lamas
on week number 2
98
Enter score for team Spittn_Lamas
on week number 3
83
Enter team name
Nut_Zippers
Enter score for team Nut_Zippers
on week number 1
70
Enter score for team Nut_Zippers
on week number 2
74
Enter score for team Nut_Zippers
on week number 3
103
Enter team name
Bucking_Broncos
Enter score for team Bucking_Broncos
on week number 1
108
Enter score for team Bucking_Broncos
on week number 2
119
Enter score for team Bucking_Broncos
on week number 3
81
********************************
output from display() with ragged output
********************************
Blind_Pigeons 123 95 121 Ave = 113
Spittn_Lamas 54 98 83 Ave = 78
Nut_Zippers 70 74 103 Ave = 82
Bucking_Broncos 108 119 81 Ave = 102
Weekly Ave: 88 96 97
********************************
output from display() using printf
********************************
Team Name Week 1 Week 2 Week 3
Blind_Pigeons 123 95 121 ave = 113
Spittn_Lamas 54 98 83 ave = 78
Nut_Zippers 70 74 103 ave = 82
Bucking_Broncos 108 119 81 ave = 102
Weekly Ave: 88 96 97
Person, Student, Family Problem
Create a class called Person. Person should have (instance variables should
be private):
private String name;
private int age;
2 Constructors:
Default constructor (no parameters)
Constructor which takes 2 parameters for name and age
Methods:
toString
equals
Nut_Zippers 70 74 103 Ave = 82
Bucking_Broncos 108 119 81 Ave = 102
Weekly Ave: 88 96 97
********************************
output from display() using printf
********************************
Team Name Week 1 Week 2 Week 3
Blind_Pigeons 123 95 121 ave = 113
Spittn_Lamas 54 98 83 ave = 78
Nut_Zippers 70 74 103 ave = 82
Bucking_Broncos 108 119 81 ave = 102
Weekly Ave: 88 96 97
Person, Student, Family Problem
Create a class called Person. Person should have (instance variables should
be private):
private String name;
private int age;
2 Constructors:
Default constructor (no parameters)
Constructor which takes 2 parameters for name and age
Methods:
toString
equals
Appropriate set and get methods for setting and accessing the Person data.
----------------------------------------------------------
Create a class called Student which extends Person.
Student has the private data:
private String major;
private double gpa;
Similar to the Person class, add get and set methods.
Add 2 constructors:
default constructor
Constructor which sets all necessary data in the Person and
Student class (name, age, major and gpa)
Methods:
toString
equals
------------------------------------------------------------
Create a Family class with the following:
Constructor:
Family (int size_of_family)
Family contains an array of Person that is the size of "size_of_family".
Family has a method called:
void addPerson(Person p);
The addPerson will call equals to make sure that the Person p
hasn't already been added. If a duplicate is found, print out
a message and continue without adding the duplicate person.
void printOutFamily();
This routine calls all of the toString methods in the family.
--------------------------------------------------------------
Run your Family with the following main routine: This output should be put
into the JH6_worksheet.txt
public static void main(String[] args)
{
Family f = new Family(8);
Person fred= new Person("Fred Flintstone", 50);
System.out.println("created " + fred);
f.addPerson(fred);
f.addPerson(fred);
Student fredStudent = new Student("Fred Flintstone", 50, "Math", 3.1);
System.out.println("created "+ fredStudent);
f.addPerson(fredStudent);
----------------------------------------------------------
Create a class called Student which extends Person.
Student has the private data:
private String major;
private double gpa;
Similar to the Person class, add get and set methods.
Add 2 constructors:
default constructor
Constructor which sets all necessary data in the Person and
Student class (name, age, major and gpa)
Methods:
toString
equals
------------------------------------------------------------
Create a Family class with the following:
Constructor:
Family (int size_of_family)
Family contains an array of Person that is the size of "size_of_family".
Family has a method called:
void addPerson(Person p);
The addPerson will call equals to make sure that the Person p
hasn't already been added. If a duplicate is found, print out
a message and continue without adding the duplicate person.
void printOutFamily();
This routine calls all of the toString methods in the family.
--------------------------------------------------------------
Run your Family with the following main routine: This output should be put
into the JH6_worksheet.txt
public static void main(String[] args)
{
Family f = new Family(8);
Person fred= new Person("Fred Flintstone", 50);
System.out.println("created " + fred);
f.addPerson(fred);
f.addPerson(fred);
Student fredStudent = new Student("Fred Flintstone", 50, "Math", 3.1);
System.out.println("created "+ fredStudent);
f.addPerson(fredStudent);
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Person wilma = new Person("Wilma Flintstone", 48);
f.addPerson(wilma);
Student george= new Student("George", 21, "Politics", 3.1);
System.out.println("created " + george);
f.addPerson(george);
george.setName("Georgie");
f.addPerson(new Student("George", 21, "Politics", 3.1));
f.addPerson(new Student("John", 18, "Geology", 2.9));
f.addPerson(new Student("Jane", 21, "Music", 3.2));
f.addPerson(new Student("Tarzan", 22, "Gymnastics", 4.0));
f.addPerson(new Student("Jim", 21, "Physics", 2.5));
f.addPerson(new Person("Robert", 18));
f.addPerson(new Person("Clemente", 32));
System.out.println("****** family listing: ");
f.printOutFamily();
}
Zoo Problem
You run a zoo which contains Animals.
So each Animal will be represented
by an abstract class.
Consider creating classes Animal, Cow, Horse, Snake, etc.
Your Animal class will have the following instance variables:
private String name;
private double weight;
f.addPerson(wilma);
Student george= new Student("George", 21, "Politics", 3.1);
System.out.println("created " + george);
f.addPerson(george);
george.setName("Georgie");
f.addPerson(new Student("George", 21, "Politics", 3.1));
f.addPerson(new Student("John", 18, "Geology", 2.9));
f.addPerson(new Student("Jane", 21, "Music", 3.2));
f.addPerson(new Student("Tarzan", 22, "Gymnastics", 4.0));
f.addPerson(new Student("Jim", 21, "Physics", 2.5));
f.addPerson(new Person("Robert", 18));
f.addPerson(new Person("Clemente", 32));
System.out.println("****** family listing: ");
f.printOutFamily();
}
Zoo Problem
You run a zoo which contains Animals.
So each Animal will be represented
by an abstract class.
Consider creating classes Animal, Cow, Horse, Snake, etc.
Your Animal class will have the following instance variables:
private String name;
private double weight;
private int age;
Your Animal class will have the following constructors:
Animal()
Animal(String n, double weight, int age)
Your Animal class will have the following methods:
String makeNoise() - this will be an abstract method
double getWeight() - returns the weight of this animal
public String toString() - returns a String with information about this Animal
***************************************
You will have the following classes which all extend Animal:
Cow, Horse, Snake.
Cow will have an instance variable called:
private int num_spots
All variables should be initialized after either of the 2 constructors:
Cow()
Cow(String name, double weight, int age, int num_spots)
You will have the methods
String makeNoise() which returns "Moooo"
toString() - returns info about all variables including Animal things
**********************************************
Horse will have an instance variable called:
private double top_speed
All variables should be initialized after either of the 2 constructors:
Horse()
Horse(String name, double weight, int age, double top_speed)
You will have the methods
String makeNoise() which returns "Whinny"
toString() - returns info about all variables including Animal things
**********************************************
Snake will have an instance variable called:
private int num_fangs
All variables should be initialized after either of the 2 constructors:
Snake()
Snake(String name, double weight, int age, int num_fangs)
You will have the methods
String makeNoise() which returns "Hisssssss"
toString() - returns info about all variables including Animal things
**********************************************
You will have a Zoo class that contains the following instance variables:
private int actual_num_animals;
private int num_cages;
private Animal[] animals;
You will have the constructors:
Zoo() - default num_cages will be 3
Zoo(int num_cages)
Your Animal class will have the following constructors:
Animal()
Animal(String n, double weight, int age)
Your Animal class will have the following methods:
String makeNoise() - this will be an abstract method
double getWeight() - returns the weight of this animal
public String toString() - returns a String with information about this Animal
***************************************
You will have the following classes which all extend Animal:
Cow, Horse, Snake.
Cow will have an instance variable called:
private int num_spots
All variables should be initialized after either of the 2 constructors:
Cow()
Cow(String name, double weight, int age, int num_spots)
You will have the methods
String makeNoise() which returns "Moooo"
toString() - returns info about all variables including Animal things
**********************************************
Horse will have an instance variable called:
private double top_speed
All variables should be initialized after either of the 2 constructors:
Horse()
Horse(String name, double weight, int age, double top_speed)
You will have the methods
String makeNoise() which returns "Whinny"
toString() - returns info about all variables including Animal things
**********************************************
Snake will have an instance variable called:
private int num_fangs
All variables should be initialized after either of the 2 constructors:
Snake()
Snake(String name, double weight, int age, int num_fangs)
You will have the methods
String makeNoise() which returns "Hisssssss"
toString() - returns info about all variables including Animal things
**********************************************
You will have a Zoo class that contains the following instance variables:
private int actual_num_animals;
private int num_cages;
private Animal[] animals;
You will have the constructors:
Zoo() - default num_cages will be 3
Zoo(int num_cages)
You will have the following methods:
void add(Animal a) - adds an animal to your Zoo
double total_weight() - returns the total weight of all animals in the zoo
void make_all_noises() - Print out the noises made by all of the animals.
In otherwords, it calls the makeNoise() method for all animals in
the zoo.
void print_all_animals() - prints the results of calling toString() on all
animals in the zoo.
************************************************
Generate output by running the following main in the Zoo class: The results
should go into the JH6_worksheet.txt
public static void main(String[] args)
{
Zoo z = new Zoo();
Snake sly = new Snake("Sly", 5.0 , 2, 2);
Snake sly2 = new Snake("Slyme", 10.0 , 1, 2);
Cow blossy = new Cow("Blossy", 900., 5, 10);
Horse prince = new Horse("Prince", 1000., 5, 23.2);
// Following not allowed because Animal is abstract
//Animal spot = new Animal("Spot", 10., 4);
z.add(sly);
z.add(sly2);
z.add(blossy);
z.add(prince);
z.make_all_noises();
System.out.println("Total weight =" + z.total_weight());
System.out.println("**************************");
System.out.println("Animal Printout:");
z.print_all_animals();
System.out.println("********* Now we will make the Second Zoo");
Zoo z2 = new Zoo(5);
z2.add(sly);
z2.add(sly2);
z2.add(blossy);
z2.add(prince);
z2.add( new Horse("Warrior", 1200, 6, 25.3));
z2.add( new Horse("Harry", 1100, 4, 21.3));
System.out.println("Total weight of z2="+z2.total_weight());
z2.make_all_noises();
z2.print_all_animals();
}
void add(Animal a) - adds an animal to your Zoo
double total_weight() - returns the total weight of all animals in the zoo
void make_all_noises() - Print out the noises made by all of the animals.
In otherwords, it calls the makeNoise() method for all animals in
the zoo.
void print_all_animals() - prints the results of calling toString() on all
animals in the zoo.
************************************************
Generate output by running the following main in the Zoo class: The results
should go into the JH6_worksheet.txt
public static void main(String[] args)
{
Zoo z = new Zoo();
Snake sly = new Snake("Sly", 5.0 , 2, 2);
Snake sly2 = new Snake("Slyme", 10.0 , 1, 2);
Cow blossy = new Cow("Blossy", 900., 5, 10);
Horse prince = new Horse("Prince", 1000., 5, 23.2);
// Following not allowed because Animal is abstract
//Animal spot = new Animal("Spot", 10., 4);
z.add(sly);
z.add(sly2);
z.add(blossy);
z.add(prince);
z.make_all_noises();
System.out.println("Total weight =" + z.total_weight());
System.out.println("**************************");
System.out.println("Animal Printout:");
z.print_all_animals();
System.out.println("********* Now we will make the Second Zoo");
Zoo z2 = new Zoo(5);
z2.add(sly);
z2.add(sly2);
z2.add(blossy);
z2.add(prince);
z2.add( new Horse("Warrior", 1200, 6, 25.3));
z2.add( new Horse("Harry", 1100, 4, 21.3));
System.out.println("Total weight of z2="+z2.total_weight());
z2.make_all_noises();
z2.print_all_animals();
}
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
As you write your code make sure you adhere to the following standards:
Rubric for Homework
In doing this assignment, make sure you satisfy the following "Rubric" :
1. In the appropriate worksheet entry, I want to see the output from your program. If your
program is not working, please say so in the worksheet entry.
DO NOT MAKE UP OUTPUT THAT DID NOT COME FROM YOUR PROGRAM ....
BE HONEST. If I find that you have submitted Source Code that is not consistent with
the Output that you claim came from your program, I will give you a zero on the whole
assignment.
2. Properly Indent your code to reflect the logic of your program.
3. Use good variable names.
4. Once we have covered methods (after chapter 3), I will expect you to use methods to
avoid putting all of your code in "main()".
stickman problem (10 points):
Create a package named stickman and add a class derived from JFrame.
ď‚· Do all the normal things like add a title to your JFrame of "My First Drawing".
ď‚· Set the size of the window to 500 by 500.
ď‚· Make the JFrame visible
ď‚· Set the default window operations on close to EXIT_ON_CLOSE
ď‚· Your class should override the method: paint(Graphics g)
ď‚· Have your paint routine draw a stick man something like the following image:
Rubric for Homework
In doing this assignment, make sure you satisfy the following "Rubric" :
1. In the appropriate worksheet entry, I want to see the output from your program. If your
program is not working, please say so in the worksheet entry.
DO NOT MAKE UP OUTPUT THAT DID NOT COME FROM YOUR PROGRAM ....
BE HONEST. If I find that you have submitted Source Code that is not consistent with
the Output that you claim came from your program, I will give you a zero on the whole
assignment.
2. Properly Indent your code to reflect the logic of your program.
3. Use good variable names.
4. Once we have covered methods (after chapter 3), I will expect you to use methods to
avoid putting all of your code in "main()".
stickman problem (10 points):
Create a package named stickman and add a class derived from JFrame.
ď‚· Do all the normal things like add a title to your JFrame of "My First Drawing".
ď‚· Set the size of the window to 500 by 500.
ď‚· Make the JFrame visible
ď‚· Set the default window operations on close to EXIT_ON_CLOSE
ď‚· Your class should override the method: paint(Graphics g)
ď‚· Have your paint routine draw a stick man something like the following image:
ď‚·
No output required for stickman ... your code will be run to see your output
No output required for stickman ... your code will be run to see your output
ellipses problem (10 points):
Create a package named ellipses and create a class derived from JFrame that produces the
following image:
HINT:
This was done by using fillOval multiple times alternating between the color
blue and
the color red. In the x,y,w, h parameters for fill oval the following
occurred:
The first oval started with x=0; y=0; w=width of screen; h = height of screen;
Create a package named ellipses and create a class derived from JFrame that produces the
following image:
HINT:
This was done by using fillOval multiple times alternating between the color
blue and
the color red. In the x,y,w, h parameters for fill oval the following
occurred:
The first oval started with x=0; y=0; w=width of screen; h = height of screen;
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
After that on each iteration you can do the following:
x += 5;
y += 5;
w -= 10;
h -= 10;
Continue looping until either w or h is <= 0
No output required for stickman ... your code will run to see your output
Tic Tac Toe Problem
Create a Tic Tac Toe Program
Sample output from your program should look like the following:
===============================e
---a------b------c---
| | | |
---d------e------f---
| | | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]e
===============================e
---a------b------c---
| | | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
x += 5;
y += 5;
w -= 10;
h -= 10;
Continue looping until either w or h is <= 0
No output required for stickman ... your code will run to see your output
Tic Tac Toe Problem
Create a Tic Tac Toe Program
Sample output from your program should look like the following:
===============================e
---a------b------c---
| | | |
---d------e------f---
| | | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]e
===============================e
---a------b------c---
| | | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]b
===============================e
---a------b------c---
| | X | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]i
===============================e
---a------b------c---
| | X | |
---d------e------f---
| | O | |
---g------h------i---
| | | O |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]a
===============================e
---a------b------c---
| X | X | |
---d------e------f---
| | O | |
---g------h------i---
| | | O |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]c
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| | O | |
---g------h------i---
| | | O |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]f
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| | O | X |
---g------h------i---
| | | O |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]g
******** We have a winner: player1: O
===============================e
---a------b------c---
| X | X | O |
Entering input for: player2: X
enter in cell [a, b, ... i]b
===============================e
---a------b------c---
| | X | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]i
===============================e
---a------b------c---
| | X | |
---d------e------f---
| | O | |
---g------h------i---
| | | O |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]a
===============================e
---a------b------c---
| X | X | |
---d------e------f---
| | O | |
---g------h------i---
| | | O |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]c
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| | O | |
---g------h------i---
| | | O |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]f
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| | O | X |
---g------h------i---
| | | O |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]g
******** We have a winner: player1: O
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| | O | X |
---g------h------i---
| O | | O |
---------------------
Do you want to play Tic-Tac-Toe (y/n)?y
===============================e
---a------b------c---
| | | |
---d------e------f---
| | | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]e
===============================e
---a------b------c---
| | | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]a
===============================e
---a------b------c---
| X | | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]c
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]g
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| | O | |
---g------h------i---
| X | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]d
| | O | X |
---g------h------i---
| O | | O |
---------------------
Do you want to play Tic-Tac-Toe (y/n)?y
===============================e
---a------b------c---
| | | |
---d------e------f---
| | | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]e
===============================e
---a------b------c---
| | | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]a
===============================e
---a------b------c---
| X | | |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]c
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| | O | |
---g------h------i---
| | | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]g
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| | O | |
---g------h------i---
| X | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]d
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| O | O | |
---g------h------i---
| X | | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]f
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]h
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | O | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]b
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | O | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]i
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | O | O |
---------------------
******** Game Ends in Draw
Do you want to play Tic-Tac-Toe (y/n)?n
Bye
************************************************************
In your JH7_worksheet.txt file, I want you to paste in at least 2 games
played. One should have a winner,
and another should be a draw. At the end, you should terminate tic_tac_toe.
---a------b------c---
| X | | O |
---d------e------f---
| O | O | |
---g------h------i---
| X | | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]f
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]h
===============================e
---a------b------c---
| X | | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | O | |
---------------------
Entering input for: player2: X
enter in cell [a, b, ... i]b
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | O | |
---------------------
Entering input for: player1: O
enter in cell [a, b, ... i]i
===============================e
---a------b------c---
| X | X | O |
---d------e------f---
| O | O | X |
---g------h------i---
| X | O | O |
---------------------
******** Game Ends in Draw
Do you want to play Tic-Tac-Toe (y/n)?n
Bye
************************************************************
In your JH7_worksheet.txt file, I want you to paste in at least 2 games
played. One should have a winner,
and another should be a draw. At the end, you should terminate tic_tac_toe.
A starting point for your program is provided (if you feel overly
constrained by this and have a better idea on structuring this
game you can create your own structure -- main should not have very much
code):
package tictactoe;
import java.util.*;
class TicTacToe
{
char ttt[][] = new char[3][3];
static final char player1 = 'O';
static final char player2 = 'X';
Scanner scan =new Scanner(System.in);
String playerID(char player)
{
// Prints the identity of the player
// For example:
// player2: X
if (player == player1)
return "player1: "+player;
else
return "player2: "+ player;
}
void getPlayerInput(char player)
{
// ******* Details to fill in ************
// Prompt the user for a cell input. Make sure its a legal
// cell designator. Also make sure the cell doesn't already
// have a player in it. Prompt the user again in the case
// of any problem. Once a valid spot has been found,
// you will issue a statement like:
ttt[row][col]=player;
}
boolean gameIsDraw()
{
// ******* Details to fill in ************
// If all ttt entries have been taken return true
// otherwise return false
}
boolean winner(char player)
{
constrained by this and have a better idea on structuring this
game you can create your own structure -- main should not have very much
code):
package tictactoe;
import java.util.*;
class TicTacToe
{
char ttt[][] = new char[3][3];
static final char player1 = 'O';
static final char player2 = 'X';
Scanner scan =new Scanner(System.in);
String playerID(char player)
{
// Prints the identity of the player
// For example:
// player2: X
if (player == player1)
return "player1: "+player;
else
return "player2: "+ player;
}
void getPlayerInput(char player)
{
// ******* Details to fill in ************
// Prompt the user for a cell input. Make sure its a legal
// cell designator. Also make sure the cell doesn't already
// have a player in it. Prompt the user again in the case
// of any problem. Once a valid spot has been found,
// you will issue a statement like:
ttt[row][col]=player;
}
boolean gameIsDraw()
{
// ******* Details to fill in ************
// If all ttt entries have been taken return true
// otherwise return false
}
boolean winner(char player)
{
// ******* Details to fill in ************
// Check to see if the parameter player has won
// Winning means that player shows up in a line of
// three. The line can be a column, row or a diagonal
// Return true if player is a winner, otherwise return false.
}
void displayBoard()
{
// ******* Details to fill in ************
// If you want to skip the fun of this, I have a candidate displayBoard
down below
}
void newgame()
{
char currPlayer = player1;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
ttt[i][j] =' ';
boolean continueFlag = true;
while (continueFlag)
{
displayBoard();
if (gameIsDraw())
{
System.out.println("Game Ends in Draw");
continueFlag = false;
}
else
{
getPlayerInput(currPlayer);
if (winner(currPlayer))
{
System.out.println("We have a winner: " +
playerID(currPlayer));
displayBoard();
continueFlag = false;
}
else
{
if (currPlayer == player1) currPlayer = player2;
else currPlayer = player1;
}
}
}
}
// Check to see if the parameter player has won
// Winning means that player shows up in a line of
// three. The line can be a column, row or a diagonal
// Return true if player is a winner, otherwise return false.
}
void displayBoard()
{
// ******* Details to fill in ************
// If you want to skip the fun of this, I have a candidate displayBoard
down below
}
void newgame()
{
char currPlayer = player1;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
ttt[i][j] =' ';
boolean continueFlag = true;
while (continueFlag)
{
displayBoard();
if (gameIsDraw())
{
System.out.println("Game Ends in Draw");
continueFlag = false;
}
else
{
getPlayerInput(currPlayer);
if (winner(currPlayer))
{
System.out.println("We have a winner: " +
playerID(currPlayer));
displayBoard();
continueFlag = false;
}
else
{
if (currPlayer == player1) currPlayer = player2;
else currPlayer = player1;
}
}
}
}
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
public static void main(String[] args)
{
TicTacToe game = new TicTacToe();
String str;
do
{
game.newgame();
System.out.println("Do you want to play Tic-Tac-Toe (y/n)?");
str= game.scan.next();
} while ("y".equals(str));
System.out.println("Bye");
}
}
By the way, I'm going to give a version of displayBoard(). This routine is a
bit
of a pain and I'm not sure how much learning happens by going through the
pain.
Also, I'm not real happy with my version, but it at least works. So... if you
want to use my version, here it is:
void displayBoard()
{
System.out.println("********************************");
System.out.println(" ---a------b------c---");
for (int i=0; i<3; i++)
{
for (int j=0; j< 3; j++)
{
if (j == 0) System.out.print(" | ");
System.out.print(ttt[i][j]);
if (j < 2) System.out.print( " | ");
if (j==2) System.out.print(" |");
}
System.out.println();
switch (i)
{
case 0:
System.out.println(" ---d------e------f---");
break;
case 1:
System.out.println(" ---g------h------i---");
break;
case 2:
System.out.println(" ---------------------");
break;
}
}
}
{
TicTacToe game = new TicTacToe();
String str;
do
{
game.newgame();
System.out.println("Do you want to play Tic-Tac-Toe (y/n)?");
str= game.scan.next();
} while ("y".equals(str));
System.out.println("Bye");
}
}
By the way, I'm going to give a version of displayBoard(). This routine is a
bit
of a pain and I'm not sure how much learning happens by going through the
pain.
Also, I'm not real happy with my version, but it at least works. So... if you
want to use my version, here it is:
void displayBoard()
{
System.out.println("********************************");
System.out.println(" ---a------b------c---");
for (int i=0; i<3; i++)
{
for (int j=0; j< 3; j++)
{
if (j == 0) System.out.print(" | ");
System.out.print(ttt[i][j]);
if (j < 2) System.out.print( " | ");
if (j==2) System.out.print(" |");
}
System.out.println();
switch (i)
{
case 0:
System.out.println(" ---d------e------f---");
break;
case 1:
System.out.println(" ---g------h------i---");
break;
case 2:
System.out.println(" ---------------------");
break;
}
}
}
1 out of 26
Related Documents
Your All-in-One AI-Powered Toolkit for Academic Success.
 +13062052269
info@desklib.com
Available 24*7 on WhatsApp / Email
Unlock your academic potential
© 2024  |  Zucol Services PVT LTD  |  All rights reserved.