CSCI 151 - Lab 1 CSCI 151 Lab 1: Four Short Java Progams Due at 6PM on Sunday, March 6. Lab Description and First Steps In this lab you will be writing a number of short programs to get some practice working with Java. The goals of this lab are to Get you to be comfortable working in Java. Learn to handle program arguments, user input and file input. Use Scanners to take input from users and files. Work with abstract classes. The zipped file Lab1.zip contains some starter code for this lab. Unzip this file, change the name of the Lab 1 folder to Lab1 and move or copy it to your CS151 folder before you go into Eclipse. Then start up Eclipse and make a new Java Project, using this Lab1 folder as its location. Each part of this lab asks you to add a new class or classes to this project. Part 1 - The Great Pyramid, revisited We will start with the Pyramid program you wrote for Lab 0. Here is a common problem: you have a class you wrote for some other purpose that you want to insert and modify for your current lab. Eclipse will help. In the Window menu at the top of Eclipse select Show View, and then in the popup menu select Project Explorer. This will show you all of your projects that Eclipse knows about. Go into the Lab0 project, and open src, then the lab0 package. You should see both of your classes from Lab 0. Click on the one with the Pyramid program; that is probably Pyramid.java. When this opens select and copy the entire file. Now make a new Class whose source folder is Lab1/src and whose package is lab1. Remove any code that appears in this class, then paste in the Pyramid program from Lab0. Presto! You just wrote a class for Lab 1 without doing any work! Isn't coding fun? You do need to make one small change -- the code you pasted was from package lab0; change the package directive at the top to lab1. Try running your Pyramid program from Lab1; it should still draw a triangle from *s and spaces. One of the goals of this lab is to see different ways to give input to a Java program, so we will modify Pyramid to take program arguments. The arguments go in the Run Configuration file. Again select Run Configurations from the Run menu. Your main class should still be indicated; if not, adjust it. In the Arguments tab give a value for the argument, perhaps 9, in the Program Arguments textbox. We aren't ready to run the program yet so click on the Apply button at the bottom of the window. Now we need to adjust the program to handle the argument. The argument to the main method is (String [ ] args). This says that variable args is an array of strings. Like all arrays, one of its properties is args.length, an integer that tells us the number of entries array args has. If this is 0 it means the user neglected to provide an argument, so we will print a reminder. If there is an argument it will be the String args[0]. We need to convert it to an integer, which we can do with the Integer.parseInt() utility method. Altogether, in your program you should replace the initial line int SIZE = 7; with the code
int SIZE=0;
if (args.length == 0) {
System.out.println( "Please specify a size.");
System.exit( -1 );
}
else
SIZE = Integer.parseInt( args[0] );
Run this version of the program (since the configuration is set up, just select Run from the Run menu) and you should get a Pyraamid of size 9, or whatever value you gave as the argument. You should try giving the configuration various arguments to ensure that your program runs reasonably for any integer arguments the user supplies. For this lab you don't need to worry about unexpected arguments (such as text strings) in the place of numeric args. Part 2 - What number am I thinking of? For this part you need to create a class called HiLo that plays a simple numeric guessing game. The computer will pick a number between 1 and 1000 and then the user will try to guess what it is. For each guess the program says if that guess is too high, too low, or correct. In one run of the program it picks one number, loops until the user guesses that number, and then quits. To facilitate the grading, please have your program print the number it chooses. Your program should be robust enough to handle non-numeric input (complain to the user if that happens). Also, keep track of the number of numeric guesses and print that count at the end of the game. The Eclipse interaction should look pretty straightforward this time. In Eclipse make a new Class, make the name of the class HiLo and put it in package lab1 with location Lab1/src. You can save yourself a line of typing it you check the box that offers to build a stub for main( ). Here are some hints to help you with this propgram: To create a random number, you will need to create a Random object called rand that will let you generate random numbers. You then can use rand.nextInt(1000) to get a number between 0 and 999. Just add 1 to get it into the right range.
Random rand = new Random();
int target = rand.nextInt(1000) + 1;
Now you'll want to loop until the user guesses your number. One way to do this is to keep a Boolean variable done that is initialized to false and is changed to true when the user gives a correct guess. In this case your loop condition will be while (!done). Another solution is to loop forever (i.e., use the loop condition while (true)) and use break to exit from the loop when the user guesses correctly. Choose one version and implement it. For the input, use a Scanner object to read from System.in which will capture keyboard input. I recommend using 2 Scanners. The first Scanner uses hasNextLine() and nextLine() to get an entire line of input from the user. Create a second Scanner using this string and then use hasNextInt() and nextInt() to see if the user actually typed a number, and if sovthen retrieve it. If the line doesn't start with a number (i.e., hasNextInt returns false) you should print a message out to the user and loop back to where you read an entire line. Here is the core of the structure:
Scanner scan = new Scanner( System.in );
int count = 0;
boolean done = false;
while (!done) {
System.out.print( "GUESS: "); // prints a prompt for the user
String line = scan.nextLine();
Scanner input = new Scanner (line); // gets the whole line of input and makes a new Scanner for it
if (input.hasNextInt()) { // checks that the input line starts with an integer
count += 1;
int guess = input.nextInt(); // gets the number the user typed
//....
// you still neeed to respond to the input
}
else
// crab at the user for not giving a number
}
}
The rest of the code is up to you. To run this, remember to update your Run Configuration to use HiLow as the main class rather than Pyramid.
Let's play a game!
I'm thinking of a number between 1 and 1000
(Don't tell anyone, but my number is 629)
Try to guess what it is!
Enter a guess: 500
Too low!
Enter a guess: 750
Too high!
Enter a guess: 625
Too low!
Enter a guess: -72
Too low!
Enter a guess: kittens
That's not a number, try again.
Enter a guess: 630
Too high!
Enter a guess: 629
You guessed my number! It took you 6 tries.
Part 3 - Longest Line From this point on we will assume you can handle the interactions with Eclipse on your own. For this part you need to write a program that reads a text file one line at a time. At the end it should print the line that contains the most words. Your program will contain variables longestLine (a String) and longestWordCount (an int). You will build a scanner that reads the file line-by-line. If a line has more words than longestWordCount you update variable longestLine with the line and variable longestWordCount with the line's word count. At the end you print longestLine. When you open a file there is always a possibility that the file won't be found, generating a FileNotFoundException. This is what Java calls a checked exception: the compiler forces you to either explicitly handle it (with a try-catch statement) or else throw it to your caller. It is bad style for main( ) to throw an exception so we will handle it ourselves. Here is code for that:
Scanner scan = null;
try {
scan = new Scanner( new File( args[0] ));
} catch(FileNotFoundException e) {
System.out.println(e);
System.exit(-1 );
} If the file is found variable scan is a scanner on it; if the file is not found an error messageis printed and we exit from the program. Note that the argument to System.exit( ) is used to explain why the progra terminated. -1 is an error code that means "something screwed up". This leads to the following program structure:
Scanner scan = null;
try {
scan = new Scanner( new File( args[0] ));
} catch(FileNotFoundException e) {
System.out.println(e);
System.exit(-1 );
}
int longestWordCount = 0;
String longestLine = "";
while (scan.hasNextLine()) {
String line = scan.nextLine();
int wordCount = ... // YOU NEED TO WRITE THE REST OF THIS
// How can you count the words on line?
// This might help: Scanner wordScanner = new Scanner(line);
if(wordCount > longestWordCount) {
longestWordCount = wordCount;
longestLine = line
}
}
System.out.printf( "The longest line is : %s\n", longestLine);
You need to count the words in String line. One easy way to do that is to open a second scanner on variable line (i.e., new Scanner( line )) and to loop through it with hasNext() and next(). The Lab1 project folder has a folder with a variety of text files. To find the longest line in the file CatInTheHat.txt use TextFiles/CatInTheHat.txt as an argument in the Run Configurations window. If you have a file name that contains spaces put quotation marks around the entire argument. Part 4 - Fighting Squirrels In this part of the lab, you will extend an abstract class. We have provided you with an abstract class, Fighter, and the code for a fighting game, called FightDriver.java. If you look at Fighter.java, you will see it has three methods that have already been written for you, and four abstract methods you will have to write yourself in any code that inherits from this class. You need to write the following methods: public int fight() : This should return a constant representing a possible fighting move. You can see that at the top of the Fighter class, we have defined four constants: BLOCK, PUNCH, KICK and FIREBALL. In order for the FightDriver code to work correctly, you will need to return one of these constants. A note about strategy: Each type of fight move has an integer value associated with it. The move takes that much energy from the fighter who uses the move, and does twice that much damage to the fighter the move is used on---if it doesn't miss. Fighters start with 50 energy, and get 15 more energy each round. If a player has negative energy they are too tired to continue and lose the fight. public String name() : This should return the name of the fighter. public String winning() : This returns a string the fighter says when they win. public String losing() : This returns a string the fighter says when they lose. You will create the following three fighter classes, each of which extends the abstract class Fighter. Pyro: Fight: If Pyro’s energy is above 30, they use the FIREBALL move. Otherwise they BLOCK. Name: Pyro Winning & Losing: You can come up with some appropriate fire related catchphrases, or use the ones from the examples below. KickyPunchy: Fight: KickyPunchy alternates between KICK and PUNCH. Name: KickyPunchy Winning & Losing: You can come up with some appropriate catchphrases, or use the ones from the examples below. FightingSquirrel : You get to design this one! Come up with whatever strategy, name, and catchphrases you like. Testing your code If you implemented everything correctly, when you compile everything and run the FightDriver code, everything should work. The fight outcomes are random, but you should get something like this The Mighty Fighting Squirrel is fighting KickyPunchy
ROUND 1 FIGHT!
The Mighty Fighting Squirrel has 100 energy
KickyPunchy has 100 energy
The Mighty Fighting Squirrel uses Kick which costs 15 energy and...misses!
KickyPunchy uses Kick which costs 15 energy and...misses!
Both fighters recover some energy
ROUND 2 FIGHT!
The Mighty Fighting Squirrel has 100 energy
KickyPunchy has 100 energy
The Mighty Fighting Squirrel uses Fireball which costs 20 energy and...misses!
KickyPunchy uses Punch which costs 10 energy and...hits!
The Mighty Fighting Squirrel loses 20 energy
Both fighters recover some energy
ROUND 3 FIGHT!
The Mighty Fighting Squirrel has 75 energy
KickyPunchy has 100 energy
The Mighty Fighting Squirrel uses Punch which costs 10 energy and...hits!
KickyPunchy loses 20 energy
KickyPunchy uses Kick which costs 15 energy and...misses!
Both fighters recover some energy
ROUND 4 FIGHT!
The Mighty Fighting Squirrel has 80 energy
KickyPunchy has 80 energy
The Mighty Fighting Squirrel uses Punch which costs 10 energy and...misses!
KickyPunchy uses Punch which costs 10 energy and...misses!
Both fighters recover some energy
ROUND 5 FIGHT!
The Mighty Fighting Squirrel has 85 energy
KickyPunchy has 85 energy
The Mighty Fighting Squirrel blocks
KickyPunchy uses Kick which costs 15 energy and...hits, but is blocked
The Mighty Fighting Squirrel loses 15 energy
Both fighters recover some energy
ROUND 6 FIGHT!
The Mighty Fighting Squirrel has 85 energy
KickyPunchy has 85 energy
The Mighty Fighting Squirrel blocks
KickyPunchy uses Punch which costs 10 energy and...misses!
Both fighters recover some energy
ROUND 7 FIGHT!
The Mighty Fighting Squirrel has 100 energy
KickyPunchy has 90 energy
The Mighty Fighting Squirrel uses Punch which costs 10 energy and...hits!
KickyPunchy loses 20 energy
KickyPunchy uses Kick which costs 15 energy and...misses!
Both fighters recover some energy
ROUND 8 FIGHT!
The Mighty Fighting Squirrel has 100 energy
KickyPunchy has 70 energy
The Mighty Fighting Squirrel blocks
KickyPunchy uses Punch which costs 10 energy and...hits, but is blocked
The Mighty Fighting Squirrel loses 10 energy
Both fighters recover some energy
ROUND 9 FIGHT!
The Mighty Fighting Squirrel has 100 energy
KickyPunchy has 75 energy
The Mighty Fighting Squirrel uses Punch which costs 10 energy and...hits!
KickyPunchy loses 20 energy
KickyPunchy uses Kick which costs 15 energy and...scores a CRITICAL HIT!!!
The Mighty Fighting Squirrel loses 45 energy
Both fighters recover some energy
ROUND 10 FIGHT!
The Mighty Fighting Squirrel has 60 energy
KickyPunchy has 55 energy
The Mighty Fighting Squirrel uses Fireball which costs 20 energy and...hits!
KickyPunchy loses 40 energy
KickyPunchy uses Punch which costs 10 energy and...misses!
Both fighters recover some energy
ROUND 11 FIGHT!
The Mighty Fighting Squirrel has 55 energy
KickyPunchy has 20 energy
The Mighty Fighting Squirrel uses Kick which costs 15 energy and...misses!
KickyPunchy uses Kick which costs 15 energy and...misses!
Both fighters recover some energy
ROUND 12 FIGHT!
The Mighty Fighting Squirrel has 55 energy
KickyPunchy has 20 energy
The Mighty Fighting Squirrel uses Punch which costs 10 energy and...misses!
KickyPunchy uses Punch which costs 10 energy and...hits!
The Mighty Fighting Squirrel loses 20 energy
Both fighters recover some energy
ROUND 13 FIGHT!
The Mighty Fighting Squirrel has 40 energy
KickyPunchy has 25 energy
The Mighty Fighting Squirrel uses Kick which costs 15 energy and...misses!
KickyPunchy uses Kick which costs 15 energy and...hits!
The Mighty Fighting Squirrel loses 30 energy
KickyPunchy wins!
KickyPunchy says "Kicking and punching towards Victory!"
The Mighty Fighting Squirrel says "Awww, nuts!" or like this
Pyro is fighting KickyPunchy
ROUND 1 FIGHT!
Pyro has 100 energy
KickyPunchy has 100 energy
Pyro uses Fireball which costs 20 energy and...misses!
KickyPunchy uses Kick which costs 15 energy and...hits!
Pyro loses 30 energy
Both fighters recover some energy
ROUND 2 FIGHT!
Pyro has 65 energy
KickyPunchy has 100 energy
Pyro uses Fireball which costs 20 energy and...hits!
KickyPunchy loses 40 energy
KickyPunchy uses Punch which costs 10 energy and...scores a CRITICAL HIT!!!
Pyro loses 30 energy
Both fighters recover some energy
ROUND 3 FIGHT!
Pyro has 30 energy
KickyPunchy has 65 energy
Pyro blocks
KickyPunchy uses Kick which costs 15 energy and...hits, but is blocked
Pyro loses 15 energy
Both fighters recover some energy
ROUND 4 FIGHT!
Pyro has 30 energy
KickyPunchy has 65 energy
Pyro blocks
KickyPunchy uses Punch which costs 10 energy and...misses!
Both fighters recover some energy
ROUND 5 FIGHT!
Pyro has 45 energy
KickyPunchy has 70 energy
Pyro uses Fireball which costs 20 energy and...hits!
KickyPunchy loses 40 energy
KickyPunchy uses Kick which costs 15 energy and...misses!
Both fighters recover some energy
ROUND 6 FIGHT!
Pyro has 40 energy
KickyPunchy has 30 energy
Pyro uses Fireball which costs 20 energy and...hits!
KickyPunchy loses 40 energy
KickyPunchy uses Punch which costs 10 energy and...misses!
Pyro wins! Pyro says "Flame on!"
KickyPunchy says "I live to kick (and/or punch) another day."`` Handing In Your Work You should have completed four programs for this lab: Pyramid, HiLo, LongestLine and the three Fighter classes for the Fightiiing squirrels program . Look through your class files and make sure you've included your name in a comment at the top of each class. If you adhered to the honor code in this assignment, add a README text file to your Lab1 folder with the text' I have adhered to the Honor Code in this assignment. You want to keep the graders happy. If there are portions of these programs that you know are not working correctly, it would be helpful if you included information about what does and what doesn't work in your README file. handin Go to your CS151 folder and make a compressed version of your Lab1 project folder. Open the Blackboard course 202109 Data Structures 01. Click on the Course Material link, then on the Lab 1 link. In the Assignment Submission section click on the Browse My Computer button. this will bring up the usual navigation controls that should allow you to select your Lab1.zip file for this assignment. Last Modified: October 2021-Bob Geitz, based on material from Roberto Hoyle, Steve Checkoway, and Benjamin Kuperman