Printstream input to a text file - java

// I'm searching for an Int in a text file, displaying that Int on console, creating a text file to print that Int. I get this instead of an Int:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=666][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]1920: ,
public static void findName(Scanner input, String name) throws FileNotFoundException {
boolean find = false;
while (find == false && input.hasNext()) {
String search = input.next();
if (search.startsWith(name) && search.endsWith(name)) {
PrintStream output = new PrintStream(new File(name + ".txt"));
output.println(name + ",");
System.out.println("1920: " + input.nextInt());
output.println("1920: " + input + ","); // need help here. HOW DO I GET THIS TO PRINT THE SAME INT, NOT GO TO THE SECOND INT?
System.out.println("1930: " + input.nextInt());
output.println("1930: " + input + ",");
System.out.println("1940: " + input.nextInt());
output.println("1940: " + input + ",");
System.out.println("1950: " + input.nextInt());
output.println("1950: " + input + ",");
System.out.println("1960: " + input.nextInt());
output.println("1960: " + input + ",");
System.out.println("1970: " + input.nextInt());
output.println("1970: " + input + ",");
System.out.println("1980: " + input.nextInt());
output.println("1980: " + input + ",");
System.out.println("1990: " + input.nextInt());
output.println("1990: " + input + ",");
System.out.println("2000: " + input.nextInt());
output.println("2000: " + input);
find = true;
}
}
if (find == false) {
System.out.println("name not found.");

you're printing the input object instead of the int into the file.
try this:
int next = input.nextInt()
System.out.println("1920: " + next );
output.println("1920: " + next + ",");
...
Hope this helps

Related

.txt array out from user input

I have since updated this code per suggestions for this forum. I am still confused as to how to get my .txt file selection to out print all instances of the name entered. my file in which all my .txt files are contained is named, namesbystate. To access this and all instances of the names entered are where I am getting issues. I am wondering if I replace myFile with namesbystate as a pathway extension or not?
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
// Scanner variable set up to intake user input for state selection and person's name
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
// nextLine variable now has the line from the file in it that matches the name the person input
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
}
}
} catch(FileNotFoundException e) {
System.out.print(e.getMessage());
}
}
}
Something like this will get you to where you want to be. I do not have the format of your state text files so I couldn't write the full program for you
(Edit - I just changed the code slightly. Instead of sc.next(), I should have written sc.nextLine(). The following program runs successfully with that edit):
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
//nextLine variable now has the line from the file in it that matches the name the person input so you need to parse that line and do something with it
}
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
}
}

How to search a token for a specific word in Java?

I have a segment of code that splits a string into tokens and prints them each out on a new line. I am having a hard time writing a code that determines if a word is a reserved word or not. I have to print "Reserved word is: " if the word is a java keyword, otherwise print "Current word is: ". Here is my code so far:
package projectweek3;
/**
*
* Name -
* Email Address -
* Date -
*
*/
public class Week3Project {
final static String program = "/*\n" +
" * To change this license header, choose License Headers in Project Properties.\n" +
" * To change this template file, choose Tools | Templates\n" +
" * and open the template in the editor.\n" +
" */\n" +
"package testapplication2;\n" +
"\n" +
"import java.util.Scanner;\n" +
"\n" +
"/**\n" +
" *\n" +
" * #author james\n" +
" */\n" +
"public class TestApplication2 {\n" +
"\n" +
" /**\n" +
" * #param args the command line arguments\n" +
" */\n" +
" public static void main(String[] args) {\n" +
" Scanner input = new Scanner(System.in);\n" +
" \n" +
" System.out.println(\"Enter integer #1\");\n" +
" int num1 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #2\");\n" +
" int num2 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #3\");\n" +
" int num3 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #4\");\n" +
" int num4 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #5\");\n" +
" int num5 = input.nextInt();\n" +
" \n" +
" //determine the sum\n" +
" int sum = num1 + num2 + num3 + num4 + num5;\n" +
" \n" +
" //this is helpful to make sure your sum is correct\n" +
" System.out.println(\"The sum is: \" + sum);\n" +
" \n" +
" //why doesn't this generate the sum correctly\n" +
" double average = sum / 5;\n" +
" \n" +
" //The average, lets hope its right...\n" +
" System.out.println(\"The average of your numbers is: \" + average);\n" +
" \n" +
" }\n" +
" \n" +
"}\n" +
"";
**public static void main(String[] args)
{
String str = program;
String s = "";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "";
if (str.charAt(i) == ' ' || str.charAt(i) == '\t' || str.charAt(i) == '\n' || (str.charAt(i) == ' ' && str.charAt(i) == '\n')) {
String currentWord = s.toString();
String res = "int";
if (currentWord.equals(res)) {
System.out.println("Reserved word is: [" + currentWord + "]");
}
else {
System.out.println("Current word is: [" + currentWord + "]");
}
s = "";//Clear the string to get it ready to build next token.
}
}**
I would reconsider the way you're looping through the "program."
Instead of going through character by character, use the Java String.split() function.
String program = "int num1 = input.nextInt();\n";
String[] words = program.split("[\\n\\s\\t]");
for (String word : words) {
System.out.println(word);
}
Output:
int
num1
=
input.nextInt();
EDIT:
Since you can't use String.split(), your looping solution looks good. To check if the current word is reserved, try using Set.contains().
Set<String> reserved = new HashSet<>();
reserved.add("int");
// ...
if reserved.contains(word) {
System.out.println("Reserved word is: " + word);
} else {
System.out.println("Current word is: " + word);
}
That is, assuming you're allowed to use Set.

Output on new line WITHOUT for loop

I am trying to output arrays on a new line through a basic client, server application. However, to accomplish this I have had to use substring to find the # after each word to signal the end of the line. However I want to remove this function and have each section on a new line.
public ClientHandler(Socket socket,Users newUser, int newClientUser)
throws IOException
{
client = socket;
input = new Scanner(client.getInputStream());
output = new PrintWriter(
client.getOutputStream(),true);
user = newUser;
clientUser = newClientUser;
String[] itemName = {user.getItemName(1), user.getItemName(2)};
String[] description = {user.getItemDescription(1), user.getItemDescription(2)};
String[] itemtime = {user.getItemTime(1), user.getItemTime(2)};
output.println(itemName[0] + "#" + itemName[1]
+ "#" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"#"+ itemName[1] +": "+description[1]+
"#"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "#" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"#");
}
private synchronized void getMessage(String response)
{
String message="";
for(int i= count; !response.substring(i, i+1).equals("#"); i++)
{
count = i;
}
}
output.println(itemName[0] + "\n" + itemName[1]
+ "\n" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"\n"+ itemName[1] +": "+description[1]+
"\n"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "\n" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"\n");
Instead of having a "#" signify a new line, you can use "\n". Java will read that from your string as a new line.

Storing Statistics in Java Calculator

Having difficulty storing the following statistics to be printed when the program terminates. I have been able to store the total number of valid and invalid expressions however I am having difficulty with the following:
The highest overall result value.
The lowest overall result value.
The aggregate of all result values, i.e. all results added together.
The average result value
Any guidance for any of the above would be much appreciated.
Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input
int validExpressions = 0;
int invalidExpressions = 0;
int lowestval = 0;
int highestval;
while (true) {
System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input
String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input
float answer; // Variable used to store answers.
if ("F".equals(choice)) {
System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file
String file = input.nextLine(); // File name will be stored in a String (file) to be used later
File txtfile = new File(file);
Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file
while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file
String expression = reader.nextLine(); // Each line is stored in a String called Expression
String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float
float number2 = Float.parseFloat(part2);
// Program processes the operator and applies it to Float number1 and Float number2 before outputting the
// expression and the correct answer
if ("+".equals(part3)) {
answer = number1 + number2;
System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(part3)) {
answer = number1 - number2;
System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(part3)) {
answer = number1 * number2;
System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(part3)) {
answer = number1 / number2;
System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
}
}
} else if ("K".equals(choice)) // If the user enters K input will be taken from the keyboard
System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression
Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input
String exp = expression.nextLine(); // The user's input is stored in a string
String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator
String element1 = elements[0];
String element2 = elements[1];
String element3 = elements[2];
float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2
float num2 = Float.parseFloat(element2);
// Program processes the operator and applies it to Float num1 and Float num2 before outputting the
// expression and the correct answer
if ("+".equals(element3)) {
answer = num1 + num2;
System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(element3)) {
answer = num1 - num2;
System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(element3)) {
answer = num1 * num2;
System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(element3)) {
answer = num1 / num2;
System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
if (choice.isEmpty()) { // If the user does not enter K or F the program will exit
System.out.println("Evaluations Complete");
System.out.println("-------------------------");
System.out.println("Valid expressions: " + validExpressions);
System.out.println("Invalid expressions: " + invalidExpressions);
System.exit(0);
}
}
}
}
}
I have changed something wrong on logic and syntax,but I have not debuged it ,you may have a try.
Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input
int validExpressions = 0;
int invalidExpressions = 0;
float lowestval = 0;
float highestval =0 ;
float total=0;
while (true) {
System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input
String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input
float answer; // Variable used to store answers.
if ("F".equals(choice)) {
System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file
String file = input.nextLine(); // File name will be stored in a String (file) to be used later
File txtfile = new File(file);
Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file
while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file
String expression = reader.nextLine(); // Each line is stored in a String called Expression
String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float
float number2 = Float.parseFloat(part2);
// Program processes the operator and applies it to Float number1 and Float number2 before outputting the
// expression and the correct answer
if ("+".equals(part3)) {
answer = number1 + number2;
System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(part3)) {
answer = number1 - number2;
System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(part3)) {
answer = number1 * number2;
System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(part3)) {
answer = number1 / number2;
System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else{
invalidExcepressions++;
continue;
}
highestval=(highestval>=answer)?highestval:answer;
lowestval=(lowestval<=answer)?lowestval:answer;
total+=answer;
}
} else if ("K".equals(choice)){ // If the user enters K input will be taken from the keyboard
System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression
Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input
String exp = expression.nextLine(); // The user's input is stored in a string
String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator
String element1 = elements[0];
String element2 = elements[1];
String element3 = elements[2];
float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2
float num2 = Float.parseFloat(element2);
// Program processes the operator and applies it to Float num1 and Float num2 before outputting the
// expression and the correct answer
if ("+".equals(element3)) {
answer = num1 + num2;
System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(element3)) {
answer = num1 - num2;
System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(element3)) {
answer = num1 * num2;
System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(element3)) {
answer = num1 / num2;
System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
}else{
invalidExceotions++;
continue;
}
highestval=(highestval>=answer)?highestval:answer;
lowestval=(lowestval<=answer)?lowestval:answer;
total+=answer;
}else if (choice.isEmpty()) { // If the user does not enter K or F the program will exit
System.out.println("Evaluations Complete");
System.out.println("-------------------------");
System.out.println("Valid expressions: " + validExpressions);
System.out.println("Invalid expressions: " + invalidExpressions);
System.out.println("Total :"+total);
System.out.println("Average :"+total/validExceptions);
System.exit(0);
}
}

Storing part of method as another method?

Basically, I have code that uses the same few lines in different scenarios, and it makes the code a bit messy (especially since I probably overcomplicated what I made, but that's another issue). What I wanted to do is store that piece of code as another function and calling it in the longer one. WHich should work as far as I know, except, the longer function has variables that aren't set in the shorter one, and if they were, I'm pretty sure it would change the final result of the function.
Here is the longer code:
public static void combat(Character a,Character b){
int battleturn = 1;
int maxTurns=20;
int draw1 = 0;
//stop after 20 turns, or stop when one player has 0 HP.
while (a.health > 0 && b.health > 0 && maxTurns > 0){
/* run a round of combat*/
if (b.health < 0.25 * b.maxHealth){
if (b.getFlee(a)){
System.out.println(">>>>>>>>>>The enemy has fled successfully<<<<<<<<<<");
break;
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + "health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}
}
As you can see there is a part of code that is repeated, and that is.
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
It won't compile if I set that chunk of code as a method, because it doesn't have the variables battleturn, maxturns, draw1, but if I put them in there, the amount of battle turns messes up.
Any ideas?
Java applications should be modular: each class fulfilling its own function, each method generally performing a single operation.
In a method you can use either class variables or its own local variables.
If you need several methods work with the same data, it should either be part of a class (instance and/or static variables) or passed to each method as parameters.
Make sure that you do not define class variables in a method. This will create local variables that will shadow class variables.
This might help you accomplish what you're trying to do.
private static void reportDamage(Character a,
Character b) {
System.out.println(a.name + " dealt "
+ a.combatRound(b) + " damage to " + b.name
+ "." + " Enemy has " + b.getHealth() + "/"
+ b.getMaxHealth() + " health.");
}
I suggest changing your combat method like this.
int battleturn = 0;
int maxTurns = 20;
// stop after 20 turns, or stop when one player has 0
// HP.
Scanner input = new Scanner(System.in);
try {
while (a.health > 0 && b.health > 0
&& battleturn < maxturn) {
battleturn++;
/* run a round of combat */
if (b.getFlee(a)) {
System.out.println(">>>>>>>>>>"
+ "The enemy has fled successfully"
+ "<<<<<<<<<<");
break;
} else {
System.out.println("Battle turn "
+ battleturn + ", <attack> or <flee>?");
boolean isFlee = false;
boolean isAttack = false;
String move = input.next();
for (;;) {
isAttack = "attack".equalsIgnoreCase(move);
isFlee = "flee".equalsIgnoreCase(move);
if (isFlee || isAttack) {
break;
}
System.out.println("Error: "
+ "Please input <attack> or <flee>.");
move = input.next();
}
if (isAttack) {
reportDamage(a, b);
reportDamage(b, a);
} else { // isFlee
if (a.getFlee(b)) {
System.out.println(">>>>>>>>>>"
+ "You have fled successfully"
+ "<<<<<<<<<<");
break;
} else {
// b is fleeing.
// reportDamage(a, b);
reportDamage(b, a);
}
}
}
}
} finally {
input.close();
}

Categories

Resources