Question

Summary Write a program that demonstrates the skills you’ve learned throughout this quarter. This type of...

Summary Write a program that demonstrates the skills you’ve learned throughout this quarter.

This type of project offers only a few guidelines and requirements, allowing you to invest as much time, effort and imagination as you want.  Submit your java programs (*.java) and any other I/O (*.txt) via Canvas  You’ve worked quite hard to make it this far, so have a bit of fun with this project!

Design Brief: Use Case Scenario You are hired to develop a program for a client who described what he wants using the following scenario: “I like to drink a beverage every morning. This might be a cup of coffee or tea. If it is coffee, I like to choose (based on wake up time) b/w espresso (short or long) or latte with one or two shots of espresso, no foam, and extra hot. If it is tea, I like to have either green or black tea; the latter can be with lemon or with half and half and sugar, depending of the kind of tea. I have a large collection of coffee and tea capsules and my beverage machine could be programmed (in Java) to make a drink at the specified time. - I would like to have a program which will allow me to set up at evening my coming morning drink. -

Sometimes, I order my beverage from my neighborhood coffee shop specifying a pick up time .” Specifications You manager and you agreed on the following specs on what the solution will look like:

Design specs

 Interactive: ask for options using UI (keyboard /Scanner or speech recognition =) ) and print out (screen) the choice

 Store data in files (read from; write to …. )

 Modular: use several classes and various methods (x2 points)

 Use test cases (aka have a driver / main) Implementation specs

 Define preconditions and postconditions

 Handle exceptions

 Use default values for your variables

 Use arrays (many kinds of coffee, tea, milk, …) for your data

 Comment and Document Rubric (100)

 5 points for every bullet in the specs above

 Compiles and run: 30 points

 Examples of output: 20 points

 Extra points for doing more

CSS 161 Requirements You are required to demonstrate 6 of the following features in your software program.

1. Functional Decomposition: Use functions to break up a large program into meaningful chunks, using input to and output from those functions where appropriate.

2. Looping with Repetition Control Structures: Use two of the following structures {for, while, do/while, foreach}.

3. Nested Loops: Use a loop within a loop in your program (see tic-tac-toe example). Note that this is automatically accomplished when using Multi-Dimensional Arrays.

4. Branching with Selection Control Structures: Use both an if/else and a switch statement in your code.

5. File IO: Read from or write to a file in your software. Examples of this include be reading in a preset pattern for the computer opponent’s answers in a game of rock/paper/scissors, or writing a file that logs each move the player makes, effectively recording a history of the game.

6. Using Multiple Classes: Build and use more than one class in your project.

7. Arrays: Make use of an Array in your software, and track its current number of live elements with an int.

8. Exception Handling with Try/Catch blocks: Add try/catch blocks to your code around possibly problematic code sections, and catch and report problems as they occur (ie, FileNotFoundException).

9. Class Design using Composition: Build a class that makes use of other preexisting classes. Your new class will “house” (or contain) the existing classes much like the AlarmClock Class contained multiple (inner) Time objects.

10. Class Design using Access Modifiers: Make all class-wide instance variables private in your class, and provide “getters” and “setters” to get and set the data accordingly. 11. Multi-Dimensional Arrays: Make use of any array with a dimensionality greater than one (see the tic-tac-toe example).

12. GUIs & Graphics (pick any one of the following) a. Use JOptionPane for message dialogs, input dialogs, etc. b. Build a Window like we did in class by using or extending a JFrame. c. Extend a JPanel and override its paint function for 2D rendering. d. Include some widgets like JButtons, JTextAreas, JComboboxes, etc.

13. Class Design using Inheritance: Since we’ve only hinted at this with our discussion, how might you accomplish this goal?

Notes

 We’ll be covering some of the examples in class and in the lab, so you’ll have a bit more guidance than just this assignment.

 Reuse, reuse, reuse! Can you accomplish multiple goals simultaneously? For example, doesn’t reading input from a file accomplish both File IO and Looping with Repetition Control Structures?

 Look in the code examples for comments and further hints – they are the key to making this assignment as simple or as complex as you like. Hints

 Use any example as a great starting point.

 Consider the Step-by-step approach outlined below in the Stepwise Refinement section.

 Don’t wait till the last minute to get started or get help. Stepwise Approach Software is frequently designed in an iterative (or stepwise) fashion. We “paint” a bit more of the big picture with each step we take, building pieces of our system and testing them as we progress. Simple projects can frequently be done by just directly attacking the problem, but for projects with many components (or classes in Java), a more formalized approach can help significantly. In this section, we’ll outline the steps required to complete this program, and suggest an approach that can be used to reduce the complexity of this project.

Step 1: File IO Choose an item above (say, File IO) and work on just that here. Focus on just getting input from a file or writing output to a file before moving on.

Step 2: Using Arrays Select a second objective (say, using arrays) and work on only that in this step. Ignoring your other goals, focus on simply declaring, using, and outputting results from your array.

Step 3,4,5,… Rinse, Refine & Repeat Select and work on only one goal at a time, taking small steps (and not giant leaps) as you progress. Make sure you’re done with and have tested the current step before proceeding to the next.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
 
public class TicTacToe
{
        public static void main(String[] args)
        {
                TicTacToe now=new TicTacToe();
                now.startGame();
        }
 
        private int[][] points;
        private int[][] winp;
        private int[] wval;
        private char[][] grid;
        private final int kcounter=3;
        private final int crosscounterer=4;
        private final int totalcount=5;
        private final int playerid=0;
        private final int compid=1;
        private final int truceid=2;
        private final int playingid=3;
        private String movesPlayer;
        private byte override;
        private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
        private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
        private Hashtable<Integer,Integer> csetter;
        private Hashtable<Integer,Integer> ksetter;
 
        public void startGame()
        {
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                System.out.print("Start?(y/n):");
                char choice='y';
                try
                {
                        choice=br.readLine().charAt(0);
                }
                catch(Exception e)
                {
                        System.out.println(e.getMessage());
                }
                if(choice=='n'||choice=='N')
                {
                        return;
                }
 
                System.out.println("Enter Grid Values, as so:\n ");
                display(numpad);
                System.out.println("Begin");
                int playerscore=0;
                int compscore=0;
                do
                {
                        int result=startGame();
                        if(result==playerid)
                                playerscore++;
                        else if(result==compid)
                                compscore++;
                        System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
                        System.out.print("Another?(y/n):");
                        try
                        {
                                choice=br.readLine().charAt(0);
                        }
                        catch(Exception e)
                        {
                                System.out.println(e.getMessage());
                        }
 
                }while(choice!='n'||choice=='N');
 
                System.out.println("Game over.");
        }
        private void put(int cell,int player)
        {
                int i=-1,j=-1;;
                switch(cell)
                {
                case 1:i=2;j=0;break;
                case 2:i=2;j=1;break;
                case 3:i=2;j=2;break;
                case 4:i=1;j=0;break;
                case 5:i=1;j=1;break;
                case 6:i=1;j=2;break;
                case 7:i=0;j=0;break;
                case 8:i=0;j=1;break;
                case 9:i=0;j=2;break;
                default:display(overridegrid);return;
                }
                char mark='x';
                if(player==0)
                        mark='o';
                grid[i][j]=mark;
                display(grid);
        }
        private int startGame()
        {
                init();
                display(grid);
                int status=playingid;
                while(status==playingid)
                {
                        put(playerMove(),0);
                        if(override==1)
                        {
                                System.out.println("O winp.");
                                return playerid;
                        }
                        status=checkForWin();
                        if(status!=playingid)
                                break;
                        try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
                        put(compMove(),1);
                        status=checkForWin();
                }
                return status;
        }
        private void init()
        {
                movesPlayer="";
                override=0;
                points=new int[8][6];
                winp=new int[][]        //new int[8][3];
                {       
                                {7,8,9},
                                {4,5,6},
                                {1,2,3},
                                {7,4,1},
                                {8,5,2},
                                {9,6,3},
                                {7,5,3},
                                {9,5,1}
                };
                wval=new int[]{3,2,3,2,4,2,3,2,3};
                grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
                csetter=new Hashtable<Integer,Integer>();
                ksetter=new Hashtable<Integer,Integer>();
        }
        private void mark(int m,int player)
        {
                for(int i=0;i<winp.length;i++)
                        for(int j=0;j<winp[i].length;j++)
                                if(winp[i][j]==m)
                                {
                                        points[i][j]=1;
                                        if(player==playerid)
                                                points[i][kcounter]++;
                                        else
                                                points[i][crosscounterer]++;
                                        points[i][totalcount]++;
                                }
        }
        private void fixwval()
        {
                for(int i=0;i<3;i++)
                        for(int j=0;j<3;j++)
                                if(points[i][j]==1)
                                        if(wval[winp[i][j]-1]!=Integer.MIN_VALUE)
                                                wval[winp[i][j]-1]=Integer.MIN_VALUE;
 
                for(int i=0;i<8;i++)
                {
                        if(points[i][totalcount]!=2)
                                continue;
                        if(points[i][crosscounterer]==2)
                        {
                                int p=i,q=-1;
                                if(points[i][0]==0)
                                        q=0;
                                else if(points[i][1]==0)
                                        q=1;
                                else if(points[i][2]==0)
                                        q=2;
 
                                if(wval[winp[p][q]-1]!=Integer.MIN_VALUE)
                                {
                                        wval[winp[p][q]-1]=6;
                                }
                        }
                        if(points[i][kcounter]==2)
                        {
                                int p=i,q=-1;
                                if(points[i][0]==0)
                                        q=0;
                                else if(points[i][1]==0)
                                        q=1;
                                else if(points[i][2]==0)
                                        q=2;
 
                                if(wval[winp[p][q]-1]!=Integer.MIN_VALUE)
                                {
                                        wval[winp[p][q]-1]=5;
                                }
                        }
                }
        }
        private int compMove()
        {
                int cell=move();
                System.out.println("Computer plays: "+cell);
                //wval[cell-1]=Integer.MIN_VALUE;
                return cell;
        }
        private int move()
        {
                int max=Integer.MIN_VALUE;
                int cell=0;
                for(int i=0;i<wval.length;i++)
                        if(wval[i]>max)
                        {
                                max=wval[i];
                                cell=i+1;
                        }
 
                //This section ensures the computer never loses
                //Remove it for a fair match
                //Dirty kluge
                if(movesPlayer.equals("76")||movesPlayer.equals("67"))
                        cell=9;
                else if(movesPlayer.equals("92")||movesPlayer.equals("29"))
                        cell=3;
                else if (movesPlayer.equals("18")||movesPlayer.equals("81"))
                        cell=7;
                else if(movesPlayer.equals("73")||movesPlayer.equals("37"))
                        cell=4*((int)(Math.random()*2)+1);
                else if(movesPlayer.equals("19")||movesPlayer.equals("91"))
                        cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));
 
                mark(cell,1);
                fixwval();
                csetter.put(cell, 0);
                return cell;
        }
        private int playerMove()
        {
                System.out.print("What's your move?: ");
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                int cell=0;
                int okay=0;
                while(okay==0)
                {
                        try
                        {
                                cell=Integer.parseInt(br.readLine());
                        }
                        catch(Exception e)
                        {
                                System.out.println(e.getMessage());
                        }
                        if(cell==7494)
                        {
                                override=1;
                                return -1;
                        }
                        if((cell<1||cell>9)||wval[cell-1]==Integer.MIN_VALUE)
                                System.out.print("Invalid move. Try again:");
                        else
                                okay=1;
                }
                playerMoved(cell);
                System.out.println();
                return cell;
        }
        private void playerMoved(int cell)
        {
                movesPlayer+=cell;
                mark(cell,0);
                fixwval();
                ksetter.put(cell, 0);
        }
        private int checkForWin()
        {
                int crossflag=0,knotflag=0;
                for(int i=0;i<winp.length;i++)
                {
                        if(csetter.containsKey(winp[i][0]))
                                if(csetter.containsKey(winp[i][1]))
                                        if(csetter.containsKey(winp[i][2]))
                                        {
                                                crossflag=1;
                                                break;
                                        }
                        if(ksetter.containsKey(winp[i][0]))
                                if(ksetter.containsKey(winp[i][1]))
                                        if(ksetter.containsKey(winp[i][2]))
                                        {
                                                knotflag=1;
                                                break;
                                        }
                }
                if(knotflag==1)
                {
                        display(grid);
                        System.out.println("O winp.");
                        return playerid;
                }
                else if(crossflag==1)
                {
                        display(grid);
                        System.out.println("X winp.");
                        return compid;
                }
 
                for(int i=0;i<wval.length;i++)
                        if(wval[i]!=Integer.MIN_VALUE)
                                return playingid;
                System.out.println("Truce");
 
                return truceid;
        }
        private void display(char[][] grid)
        {
                for(int i=0;i<3;i++)
                {
                        System.out.println("\n-------");
                        System.out.print("|");
                        for(int j=0;j<3;j++)
                                System.out.print(grid[i][j]+"|");
                }
                System.out.println("\n-------");
        }
}
Add a comment
Know the answer?
Add Answer to:
Summary Write a program that demonstrates the skills you’ve learned throughout this quarter. This type of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the ...

    Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the merge sort algorithm. The basic steps of merge sort are: 1) divide a collection of items into two lists of equal size, 2) use merge sort to separately sort each of the two lists, and 3) combine the two sorted lists into one sorted list. Of course, if the collection of items is just asingle item then merge sort doesn’t need to perform the three steps,...

  • Parallel Arrays Summary In this lab, you use what you have learned about parallel arrays to...

    Parallel Arrays Summary In this lab, you use what you have learned about parallel arrays to complete a partially completed Java program. The program should either print the name and price for a coffee add-in from the Jumpin’ Jive coffee shop or it should print the message: "Sorry, we do not carry that.". Read the problem description carefully before you begin. The data file provided for this lab includes the necessary variable declarations and input statements. You need to write...

  • I need help with my assignment. It is a java program. Please make it as simple...

    I need help with my assignment. It is a java program. Please make it as simple as you can. Create an ArrayList with elements the objects of previous class. Using a simple loop populate the ArrayList with data from some arrays with data, or from console. Use a loop with iterator and write the information in a File using PrintWriter. Use this address for the file (c:\\result\\MyData.txt). Use the Scanner class to display the content of the file on console.

  • plz write if it is in another class or package Question 1: 1. Create a new...

    plz write if it is in another class or package Question 1: 1. Create a new project in Eclipse (File > New > Java Project.) Name it Homework2Q1 2. Create a package for your classes 3. Create an abstract superclass with only non default constructor(s) 4. Create two different subclasses of that superclass 5. Create another class that is not related (you need a total of four classes up to this point) 6. Create an interface 7. Make the class...

  • The purpose of this project is to give students more exposure to object oriented design and...

    The purpose of this project is to give students more exposure to object oriented design and programming using classes and polymorphism in a realistic application that involves arrays of objects and sorting arrays containing objects A large veterinarian services many pets and their owners. As new pets are added to the population of pets being serviced, their information is entered into a flat text file. Each month the vet requests and updates listing of all pets sorted by their "outstanding...

  • package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task...

    package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task #1 before adding Task#2 where indicated. */ public class NumericTypesOriginal { public static void main (String [] args) { //TASK #2 Create a Scanner object here //identifier declarations final int NUMBER = 2 ; // number of scores int score1 = 100; // first test score int score2 = 95; // second test score final int BOILING_IN_F = 212; // boiling temperature double fToC;...

  • Concepts Tested in this Program: Class Design Constructors Objects Inheritance Program:   Design a class named Person...

    Concepts Tested in this Program: Class Design Constructors Objects Inheritance Program:   Design a class named Person and its two subclasses, Student and Employee. Make Faculty and Staff subclasses of Employee. A Person object has a name, address, phone number, and email address (all Strings). A Student Object has a class status (freshman, sophomore, junior, or senior). Define the status as a final String variable. An Employee Object has an office number, salary (both ints ), and a date hired. Use...

  • Write and submit one complete Java program to solve the following requirements. Your program will employ...

    Write and submit one complete Java program to solve the following requirements. Your program will employ packages (that is, source directories), and contain multiple source files. Because you are using packages, your code should be in a directory named “Greenhouse.” You should be able to compile your code using the command “javac Greenhouse\*.java” from a directory just below the Greenhouse directory. In the program for this assignment, class names have been specified. You mustuse the supplied class name for both...

  • Please help me code the following in: JAVA Please create the code in as basic way...

    Please help me code the following in: JAVA Please create the code in as basic way as possible, so I can understand it better :) Full points will be awarded, thanks in advance! Program Description Write a program that demonstrates the skills we've learned throughout this quarter. This type of project offers only a few guidelines, allowing you to invest as much time and polish as you want, as long as you meet the program requirements described below. You can...

  • Count Occurrences in Seven Integers Using Java Single Dimension Arrays In this assignment, you will design...

    Count Occurrences in Seven Integers Using Java Single Dimension Arrays In this assignment, you will design and code a Java console application that reads in seven integer values and prints out the number of occurrences of each value. The application uses the Java single dimension array construct to implement its functionality. Your program output should look like the sample output provided in the "Count Occurrences in Seven Integers Using Java Single Dimension Arrays Instructions" course file resource. Full instructions for...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT