How can I limit the user to spend a "Tag" on a different "Skill" on each inputFirstTag, inputSecondTag, inputThirdTag
Everything works fine until Round 2 rears its ugly head. inputSecondTag can become a duplicate of inputFirstTag, inputThirdTag can become a duplicate of inputSecondTag.
System.out.println("You have 3 Skills to Tag.");
System.out.println("What skill would you like to Tag? (+25)");
System.out.print("Small Guns, Big Guns, Energy Weapons, Unarmed, Melee Weapons, Throwing, ");
System.out.print("First Aid, Doctor, Sneak, Lockpick, Steal, Traps, Science, Repair, ");
System.out.println("Speech, Barter, Gambling or Outdoors?");
Scanner scanFirstTag = new Scanner(System.in);
String inputFirstTag = null;
while (scanFirstTag.hasNextLine()) {
inputFirstTag = scanFirstTag.nextLine();
if (inputFirstTag.equalsIgnoreCase("Small Guns") || inputFirstTag.equalsIgnoreCase("Big Guns") ||
inputFirstTag.equalsIgnoreCase("Energy Weapons") || inputFirstTag.equalsIgnoreCase("Unarmed") ||
inputFirstTag.equalsIgnoreCase("Melee Weapons") || inputFirstTag.equalsIgnoreCase("Throwing") ||
inputFirstTag.equalsIgnoreCase("First Aid") || inputFirstTag.equalsIgnoreCase("Doctor") ||
inputFirstTag.equalsIgnoreCase("Sneak") || inputFirstTag.equalsIgnoreCase("Lockpick") ||
inputFirstTag.equalsIgnoreCase("Steal") || inputFirstTag.equalsIgnoreCase("Traps") ||
inputFirstTag.equalsIgnoreCase("Science") || inputFirstTag.equalsIgnoreCase("Repair") ||
inputFirstTag.equalsIgnoreCase("Speech") || inputFirstTag.equalsIgnoreCase("Barter") ||
inputFirstTag.equalsIgnoreCase("Gambling") || inputFirstTag.equalsIgnoreCase("Outdoors"))
break;
else System.out.println("Please choose Small Guns, Big Guns, Energy Weapons, " +
"Unarmed, Melee Weapons, Throwing, First Aid, Doctor, " +
"Sneak, Lockpick, Steal, Traps, Science, Repair, " +
"Speech, Barter, Gambling or Outdoors?");
}
if (inputFirstTag.equalsIgnoreCase("Small Guns")) {
System.out.println("Small Guns Increased by 25!");
smallGuns = smallGuns + 25;
System.out.println("Small Guns: " + smallGuns);
} else if (inputFirstTag.equalsIgnoreCase("Big Guns")) {
System.out.println("Big Guns Increased by 25!");
bigGuns = bigGuns + 25;
System.out.println("Big Guns: " + bigGuns);
} else if (inputFirstTag.equalsIgnoreCase("Energy Weapons")) {
System.out.println("Energy Weapons Increased by 25!");
energyWeapons = energyWeapons + 25;
System.out.println("Energy Weapons: " + energyWeapons);
} else if (inputFirstTag.equalsIgnoreCase("Unarmed")) {
System.out.println("Unarmed Increased by 25!");
unarmed = unarmed + 25;
System.out.println("Unarmed: " + unarmed);
} else if (inputFirstTag.equalsIgnoreCase("Melee Weapons")) {
System.out.println("Melee Weapons Increased by 25!");
meleeWeapons = meleeWeapons+ 25;
System.out.println("Melee Weapons: " + meleeWeapons);
} else if (inputFirstTag.equalsIgnoreCase("Throwing")) {
System.out.println("Throwing Increased by 25!");
throwing = throwing + 25;
System.out.println("Throwing: " + throwing);
} else if (inputFirstTag.equalsIgnoreCase("First Aid")) {
System.out.println("First Aid Increased by 25!");
firstAid = firstAid+ 25;
System.out.println("First Aid: " + firstAid);
} else if (inputFirstTag.equalsIgnoreCase("Doctor")) {
System.out.println("Doctor Increased by 25!");
doctor = doctor + 25;
System.out.println("Doctor: " + doctor);
} else if (inputFirstTag.equalsIgnoreCase("Sneak")) {
System.out.println("Sneak Increased by 25!");
sneak = sneak + 25;
System.out.println("Sneak: " + sneak);
} else if (inputFirstTag.equalsIgnoreCase("Lockpick")) {
System.out.println("Lockpick Increased by 25!");
lockpick = lockpick + 25;
System.out.println("Lockpick: " + lockpick);
} else if (inputFirstTag.equalsIgnoreCase("Steal")) {
System.out.println("Steal Increased by 25!");
steal = steal + 25;
System.out.println("Steal: " + steal);
} else if (inputFirstTag.equalsIgnoreCase("Traps")) {
System.out.println("Traps Increased by 25!");
traps = traps + 25;
System.out.println("Traps: " + traps);
} else if (inputFirstTag.equalsIgnoreCase("Science")) {
System.out.println("Science Increased by 25!");
science = science + 25;
System.out.println("Science: " + science);
} else if (inputFirstTag.equalsIgnoreCase("Repair")) {
System.out.println("Repair Increased by 25!");
repair = repair + 25;
System.out.println("Repair: " + repair);
} else if (inputFirstTag.equalsIgnoreCase("Speech")) {
System.out.println("Speech Increased by 25!");
speech = speech + 25;
System.out.println("Speech: " + speech);
} else if (inputFirstTag.equalsIgnoreCase("Barter")) {
System.out.println("Barter Increased by 25!");
barter = barter + 25;
System.out.println("Barter: " + barter);
} else if (inputFirstTag.equalsIgnoreCase("Gambling")) {
System.out.println("Gambling Increased by 25!");
gambling = gambling + 25;
System.out.println("Gambling: " + gambling);
} else if (inputFirstTag.equalsIgnoreCase("Outdoors")) {
System.out.println("Outdoors Increased by 25!");
outdoors = outdoors + 25;
System.out.println("Outdoors: " + outdoors);
}
System.out.println();
System.out.println("You have 2 Skills to Tag.");
System.out.println("What skill would you like to Tag? (+20)");
System.out.print("Small Guns, Big Guns, Energy Weapons, Unarmed, Melee Weapons, Throwing, ");
System.out.print("First Aid, Doctor, Sneak, Lockpick, Steal, Traps, Science, Repair, ");
System.out.println("Speech, Barter, Gambling or Outdoors?");
Scanner scanSecondTag = new Scanner(System.in);
String inputSecondTag = null;
while (scanSecondTag.hasNextLine()) {
inputSecondTag = scanSecondTag.nextLine();
if (inputSecondTag.equalsIgnoreCase("Small Guns") || inputSecondTag.equalsIgnoreCase("Big Guns") || inputSecondTag.equalsIgnoreCase("Energy Weapons") || inputSecondTag.equalsIgnoreCase("Unarmed") || inputSecondTag.equalsIgnoreCase("Melee Weapons") || inputSecondTag.equalsIgnoreCase("Throwing") || inputSecondTag.equalsIgnoreCase("First Aid") || inputSecondTag.equalsIgnoreCase("Doctor") ||
inputSecondTag.equalsIgnoreCase("Sneak") || inputSecondTag.equalsIgnoreCase("Lockpick") ||
inputSecondTag.equalsIgnoreCase("Steal") || inputSecondTag.equalsIgnoreCase("Traps") ||
inputSecondTag.equalsIgnoreCase("Science") || inputSecondTag.equalsIgnoreCase("Repair") ||
inputSecondTag.equalsIgnoreCase("Speech") || inputSecondTag.equalsIgnoreCase("Barter") ||
inputSecondTag.equalsIgnoreCase("Gambling") || inputSecondTag.equalsIgnoreCase("Outdoors"))
break;
else System.out.println("Please choose Small Guns, Big Guns, Energy Weapons, " +
"Unarmed, Melee Weapons, Throwing, First Aid, Doctor, " +
"Sneak, Lockpick, Steal, Traps, Science, Repair, " +
"Speech, Barter, Gambling or Outdoors?");
}
if (inputSecondTag.equalsIgnoreCase("Small Guns")) {
System.out.println("Small Guns Increased by 20!");
smallGuns = smallGuns + 20;
System.out.println("Small Guns: " + smallGuns);
} else if (inputSecondTag.equalsIgnoreCase("Big Guns")) {
System.out.println("Big Guns Increased by 20!");
bigGuns = bigGuns + 20;
System.out.println("Big Guns: " + bigGuns);
} else if (inputSecondTag.equalsIgnoreCase("Energy Weapons")) {
System.out.println("Energy Weapons Increased by 20!");
energyWeapons = energyWeapons + 20;
System.out.println("Energy Weapons: " + energyWeapons);
} else if (inputSecondTag.equalsIgnoreCase("Unarmed")) {
System.out.println("Unarmed Increased by 20!");
unarmed = unarmed + 20;
System.out.println("Unarmed: " + unarmed);
} else if (inputSecondTag.equalsIgnoreCase("Melee Weapons")) {
System.out.println("Melee Weapons Increased by 20!");
meleeWeapons = meleeWeapons+ 20;
System.out.println("Melee Weapons: " + meleeWeapons);
} else if (inputSecondTag.equalsIgnoreCase("Throwing")) {
System.out.println("Throwing Increased by 20!");
throwing = throwing + 20;
System.out.println("Throwing: " + throwing);
} else if (inputSecondTag.equalsIgnoreCase("First Aid")) {
System.out.println("First Aid Increased by 20!");
firstAid = firstAid+ 20;
System.out.println("First Aid: " + firstAid);
} else if (inputSecondTag.equalsIgnoreCase("Doctor")) {
System.out.println("Doctor Increased by 20!");
doctor = doctor + 20;
System.out.println("Doctor: " + doctor);
} else if (inputSecondTag.equalsIgnoreCase("Sneak")) {
System.out.println("Sneak Increased by 20!");
sneak = sneak + 20;
System.out.println("Sneak: " + sneak);
} else if (inputSecondTag.equalsIgnoreCase("Lockpick")) {
System.out.println("Lockpick Increased by 20!");
lockpick = lockpick + 20;
System.out.println("Lockpick: " + lockpick);
} else if (inputSecondTag.equalsIgnoreCase("Steal")) {
System.out.println("Steal Increased by 20!");
steal = steal + 20;
System.out.println("Steal: " + steal);
} else if (inputSecondTag.equalsIgnoreCase("Traps")) {
System.out.println("Traps Increased by 20!");
traps = traps + 20;
System.out.println("Traps: " + traps);
} else if (inputSecondTag.equalsIgnoreCase("Science")) {
System.out.println("Science Increased by 20!");
science = science + 20;
System.out.println("Science: " + science);
} else if (inputSecondTag.equalsIgnoreCase("Repair")) {
System.out.println("Repair Increased by 20!");
repair = repair + 20;
System.out.println("Repair: " + repair);
} else if (inputSecondTag.equalsIgnoreCase("Speech")) {
System.out.println("Speech Increased by 20!");
speech = speech + 20;
System.out.println("Speech: " + speech);
} else if (inputSecondTag.equalsIgnoreCase("Barter")) {
System.out.println("Barter Increased by 20!");
barter = barter + 20;
System.out.println("Barter: " + barter);
} else if (inputSecondTag.equalsIgnoreCase("Gambling")) {
System.out.println("Gambling Increased by 20!");
gambling = gambling + 20;
System.out.println("Gambling: " + gambling);
} else if (inputSecondTag.equalsIgnoreCase("Outdoors")) {
System.out.println("Outdoors Increased by 20!");
outdoors = outdoors + 20;
System.out.println("Outdoors: " + outdoors);
}
System.out.println();
System.out.println("You have 1 Skill to Tag.");
System.out.println("What skill would you like to Tag? (+15)");
System.out.print("Small Guns, Big Guns, Energy Weapons, Unarmed, Melee Weapons, Throwing, ");
System.out.print("First Aid, Doctor, Sneak, Lockpick, Steal, Traps, Science, Repair, ");
System.out.println("Speech, Barter, Gambling or Outdoors?");
Scanner scanThirdTag = new Scanner(System.in);
String inputThirdTag = null;
while (scanThirdTag.hasNextLine()) {
inputThirdTag = scanThirdTag.nextLine();
if (inputThirdTag.equalsIgnoreCase("Small Guns") || inputThirdTag.equalsIgnoreCase("Big Guns") || inputThirdTag.equalsIgnoreCase("Energy Weapons") || inputThirdTag.equalsIgnoreCase("Unarmed") || inputThirdTag.equalsIgnoreCase("Melee Weapons") || inputThirdTag.equalsIgnoreCase("Throwing") || inputThirdTag.equalsIgnoreCase("First Aid") || inputThirdTag.equalsIgnoreCase("Doctor") ||
inputThirdTag.equalsIgnoreCase("Sneak") || inputThirdTag.equalsIgnoreCase("Lockpick") ||
inputThirdTag.equalsIgnoreCase("Steal") || inputThirdTag.equalsIgnoreCase("Traps") ||
inputThirdTag.equalsIgnoreCase("Science") || inputThirdTag.equalsIgnoreCase("Repair") ||
inputThirdTag.equalsIgnoreCase("Speech") || inputThirdTag.equalsIgnoreCase("Barter") ||
inputThirdTag.equalsIgnoreCase("Gambling") || inputThirdTag.equalsIgnoreCase("Outdoors"))
break;
else System.out.println("Please choose Small Guns, Big Guns, Energy Weapons, " +
"Unarmed, Melee Weapons, Throwing, First Aid, Doctor, " +
"Sneak, Lockpick, Steal, Traps, Science, Repair, " +
"Speech, Barter, Gambling or Outdoors?");
}
if (inputThirdTag.equalsIgnoreCase("Small Guns")) {
System.out.println("Small Guns Increased by 25!");
smallGuns = smallGuns + 25;
System.out.println("Small Guns: " + smallGuns);
} else if (inputThirdTag.equalsIgnoreCase("Big Guns")) {
System.out.println("Big Guns Increased by 25!");
bigGuns = bigGuns + 25;
System.out.println("Big Guns: " + bigGuns);
} else if (inputThirdTag.equalsIgnoreCase("Energy Weapons")) {
System.out.println("Energy Weapons Increased by 25!");
energyWeapons = energyWeapons + 25;
System.out.println("Energy Weapons: " + energyWeapons);
} else if (inputThirdTag.equalsIgnoreCase("Unarmed")) {
System.out.println("Unarmed Increased by 25!");
unarmed = unarmed + 25;
System.out.println("Unarmed: " + unarmed);
} else if (inputThirdTag.equalsIgnoreCase("Melee Weapons")) {
System.out.println("Melee Weapons Increased by 25!");
meleeWeapons = meleeWeapons+ 25;
System.out.println("Melee Weapons: " + meleeWeapons);
} else if (inputThirdTag.equalsIgnoreCase("Throwing")) {
System.out.println("Throwing Increased by 25!");
throwing = throwing + 25;
System.out.println("Throwing: " + throwing);
} else if (inputThirdTag.equalsIgnoreCase("First Aid")) {
System.out.println("First Aid Increased by 25!");
firstAid = firstAid+ 25;
System.out.println("First Aid: " + firstAid);
} else if (inputThirdTag.equalsIgnoreCase("Doctor")) {
System.out.println("Doctor Increased by 25!");
doctor = doctor + 25;
System.out.println("Doctor: " + doctor);
} else if (inputThirdTag.equalsIgnoreCase("Sneak")) {
System.out.println("Sneak Increased by 25!");
sneak = sneak + 25;
System.out.println("Sneak: " + sneak);
} else if (inputThirdTag.equalsIgnoreCase("Lockpick")) {
System.out.println("Lockpick Increased by 25!");
lockpick = lockpick + 25;
System.out.println("Lockpick: " + lockpick);
} else if (inputThirdTag.equalsIgnoreCase("Steal")) {
System.out.println("Steal Increased by 25!");
steal = steal + 25;
System.out.println("Steal: " + steal);
} else if (inputThirdTag.equalsIgnoreCase("Traps")) {
System.out.println("Traps Increased by 25!");
traps = traps + 25;
System.out.println("Traps: " + traps);
} else if (inputThirdTag.equalsIgnoreCase("Science")) {
System.out.println("Science Increased by 25!");
science = science + 25;
System.out.println("Science: " + science);
} else if (inputThirdTag.equalsIgnoreCase("Repair")) {
System.out.println("Repair Increased by 25!");
repair = repair + 25;
System.out.println("Repair: " + repair);
} else if (inputThirdTag.equalsIgnoreCase("Speech")) {
System.out.println("Speech Increased by 25!");
speech = speech + 25;
System.out.println("Speech: " + speech);
} else if (inputThirdTag.equalsIgnoreCase("Barter")) {
System.out.println("Barter Increased by 25!");
barter = barter + 25;
System.out.println("Barter: " + barter);
} else if (inputThirdTag.equalsIgnoreCase("Gambling")) {
System.out.println("Gambling Increased by 25!");
gambling = gambling + 25;
System.out.println("Gambling: " + gambling);
} else if (inputThirdTag.equalsIgnoreCase("Outdoors")) {
System.out.println("Outdoors Increased by 25!");
outdoors = outdoors + 25;
System.out.println("Outdoors: " + outdoors);
}
System.out.println();
System.out.println(enter);
pressEnter.nextLine();
System.out.println("Your new Skills are:");
System.out.println("Small Guns: " + smallGuns);
System.out.println("Big Guns: " + bigGuns);
System.out.println("Energy Weapons: " + energyWeapons);
System.out.println("Unarmed: " + unarmed);
System.out.println("Melee Weapons: " + meleeWeapons);
System.out.println("Throwing: " + throwing);
System.out.println("First Aid: " + firstAid);
System.out.println("Doctor: " + doctor);
System.out.println("Sneak: " + sneak);
System.out.println("Lockpick: " + lockpick);
System.out.println("Steal: " + steal);
System.out.println("Traps: " + traps);
System.out.println("Science: " + science);
System.out.println("Repair: " + repair);
System.out.println("Speech: " + speech);
System.out.println("Barter: " + barter);
System.out.println("Gambling: " + gambling);
System.out.println("Outdoors: " + outdoors);
System.out.println();
System.out.println(enter);
pressEnter.nextLine();
}
}
Without overwhelming you with a long block of code:
You can create a Set data structure of "taggedSkills." Initially, this Set is empty. If the user tags a skill, the skill is added to the set.
Then if the user's second tag is the same skill as the first tag, the program can check the Set and ask the user to try again with a new skill, instead of adding a duplicate tag. Same with the third skill.
This isn't perfect, and I didn't feel like typing all the choices, but this might help you.
import java.util.ArrayList;
import java.util.Scanner;
public class Meow {
public static void main(String[] args){
ArrayList<String> choices = new ArrayList<String>();
choices.add("Barter");
choices.add("Repair");
choices.add("Speech");
choices.add("Potato");
int[] numbers = new int[choices.size()];
System.out.println("You have 3 Skills to Tag.");
System.out.println("What skill would you like to Tag? (+25)");
System.out.println("Barter, Repair, Speech, Potato?");
Scanner scanner = new Scanner(System.in);
String inputFirstTag = "";
while (scanner.hasNextLine()) {
inputFirstTag = scanner.nextLine();
if ((choices.contains(inputFirstTag))){
if(numbers[choices.indexOf(inputFirstTag)] == 0){
numbers[choices.indexOf(inputFirstTag)] += 25;
break;
}
else {System.out.println("Please don't choose duplicates");}
}
else {System.out.println("Please choose Repair, Speech, Barter.");}
}
System.out.println(inputFirstTag + " + 25");
System.out.println();
System.out.println("You have 2 Skills to Tag.");
System.out.println("What skill would you like to Tag? (+25)");
System.out.println("Barter, Repair, Speech, Potato?");
String inputSecondTag = "";
while (scanner.hasNextLine()) {
inputSecondTag = scanner.nextLine();
if ((choices.contains(inputSecondTag))){
if(numbers[choices.indexOf(inputSecondTag)] == 0){
numbers[choices.indexOf(inputSecondTag)] += 25;
break;
}
else {System.out.println("Please don't choose duplicates");}
}
else {System.out.println("Please choose Repair, Speech, Barter.");}
}
System.out.println(inputSecondTag + " + 25");
System.out.println();
System.out.println();
System.out.println("You have 1 Skill to Tag.");
System.out.println("What skill would you like to Tag? (+25)");
System.out.println("Barter, Repair, Speech, Potato?");
String inputThirdTag = "";
while (scanner.hasNextLine()) {
inputThirdTag = scanner.nextLine();
if ((choices.contains(inputThirdTag))){
if(numbers[choices.indexOf(inputThirdTag)] == 0){
numbers[choices.indexOf(inputThirdTag)] += 25;
break;
}
else {System.out.println("Please don't choose duplicates");}
}
else {System.out.println("Please choose Repair, Speech, Barter.");}
}
System.out.println(inputThirdTag + " + 25");
System.out.println();
for (int i = 0; i < choices.size(); i++){
System.out.println(choices.get(i) + " : " + numbers[i]);
}
}
}
My version.
import java.util.*;
public class SOFQuestion {
private static Skill getSkillFromUser() {
final Scanner scanFirstTag = new Scanner(System.in);
while (scanFirstTag.hasNextLine()) {
final String inputFirstTag = scanFirstTag.nextLine();
for (Skill skill : Skill.values()) {
if (skill.getSkillName().equalsIgnoreCase(inputFirstTag)) {
if (Skill.alreadyAddedSkills.contains(skill)) {
System.out.println("Sorry, but you have are already increased this skill.");
break;
}
return skill;
}
}
System.out.println("Please choose " + Skill.getSkillsList() + "?");
}
return null;
}
enum Skill {
SMALL_GUNS("Small Guns"),
THROWING("Throwing"),
FIRST_AID("First Aid"),
DOCTOR("Doctor");
private final String skillName;
private int skillPower;
private static List<Skill> alreadyAddedSkills = new ArrayList<>();
Skill(String skillName) {
this.skillName = skillName;
}
public String getSkillName() {
return skillName;
}
public int getSkillPower() {
return skillPower;
}
public void increaseSkillPower(int skillPower) {
this.skillPower += skillPower;
alreadyAddedSkills.add(this);
System.out.println("You increase " + getSkillName() + " skill to " + getSkillPower());
}
public static String getSkillsList() {
final StringBuffer sb = new StringBuffer();
for (Skill s : Skill.values()) {
if (alreadyAddedSkills.contains(s)) continue;
sb.append(s.getSkillName()).append(", ");
}
if (sb.length() > 2) {
return sb.toString().substring(0, sb.length() - 2);
}
return "EMPTY SKILL LIST";
}
}
public static void main(String... args) {
int skillLimit = 3;
int defPower = 10;
while (skillLimit != 0) {
final int powerToAdd = skillLimit * 5 + defPower;
System.out.println("You have " + skillLimit-- + " Skills to Tag.");
System.out.println("What skill would you like to Tag? " + "(+" + powerToAdd + ")");
System.out.println(Skill.getSkillsList() + "?");
final Skill skill = getSkillFromUser();
if (skill == null) return;
skill.increaseSkillPower(powerToAdd);
}
System.out.println("Your new Skills are:");
for (Skill skill : Skill.values()) {
System.out.println(skill.getSkillName() + ": " + skill.getSkillPower());
}
}
}
Related
I am stuck at a part where in a game, I use while loop and to end the loop and get the results of the game, I want either "player1" or "player2" to enter "Q", and so i tried doing it like this:
if (player1.equals("Q") || player2.equals("Q")){
go = false; //go is a boolean variable
}
This doesn't seem to work as I have to enter "Q" for both player1 and player2 for the game to end, but instead I just want either of them to enter "Q" and the game would stop.
Code:
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Soccer Game Between 2 Teams");
System.out.println("Win is 2 points" + "\n" + "Loss is worth 0 points" + "\n" + "Overtime is worth 1 point");
System.out.println("Type W, O, or L" + "\n" + "Type Q to end the game");
int pointsw = 0;
int pointsl = 0;
int pointso = 0;
int pointsw2 = 0;
int pointsl2 = 0;
int pointso2 = 0;
int totalpoints = 0;
int totalpoints2 = 0;
int counter = 0;
int counter2 = 0;
boolean go = true;
System.out.println("\n" + "Enter team one:");
String phrase = keyboard.next();
System.out.println("\n" + "Enter team two:");
String phrase2 = keyboard.next();
System.out.println();
while (go) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next();
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next();
if (team1.equals("W") || team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("O") || team1.equals("o")) {
pointso += 1;
} else if (team1.equals("L") || team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("W") || team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("O") || team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("L") || team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
if (team1.equals("Q") || team2.equals("Q")) {
go = false;
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
}
}
}
}
You should reorganize your code:
while (true) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next().toLowerCase();
if ("q".equals(team1)) {
break;
}
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next().toLowerCase();
if ("q".equals(team2)) {
break;
}
if (team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("o")) {
pointso += 1;
} else if (team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
} // loop completed
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
I'm not completely sure, but I think the issue is that after player 1 / player 2 says 'Q'
the scanner is still waiting for the next line to read.
String phrase = keyboard.next();
System.out.println("\n"+"Enter team two:");
String phrase2 = keyboard.next();//if player 1 types q this next() method must be resolved before it will continue to the logic
so add an if statement before play 2 goes asking if player 1 typed 'Q' , if so calculate scores and end game, if player 1 did not type 'Q' use else statement to continue on to player 2's turn
I'm writing a party planner program for a question for class.
I can't initialize my three choices of entertainment, decorations, and food.
Eclipse tells me that I should set all these values to 0. I have to stick to these if else statements because that's what we have learned so far.
Here is my code:
import java.util.Scanner;
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
int budget = entertainment + decorations + food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}
The problem is
The local variable entertainment, decorations, and food may have not been initalized.
First , you have to make the sum at the end of the code because at first the variables are not initialized yet , and secondly you can assign a value of zero if no choice have been made , like this :
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
else { entertainment = 0; }
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
else { decorations = 0; }
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
else { food = 0 ; }
int budget = entertainment + decorations + food;
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}
My final project for class is a text based game. So far I have it working how I want, except for 1 or 2 issues. First big issue is when I enter my "magic" menu (switch statement loop) none of the data has any impact. Meaning if the user's HP drops below 0, they don't die, it doesn't happen until you exit the loop. I've messed with it, and made it work, but it broke other parts of the code, so please help if you can.
Another solution I was able to do was setting the boolean value to false after each case, making the user enter a case, then it jumps out of the switch, which works great, except it executes the entire switch loop, meaning every single input.
Here's the main code, keep in mind it has another class
package textRPG;
import java.util.Random;
import java.util.Scanner;
public class LoopyLoop {
private static int maxEnemyHealth = 155;
private static int enemyAttackDmg = 25;
private static int health = 109;
private static int attackDmg = 30;
private static int mana = 15;
private static int numHealthPots = 3;
private static int healthPotionHealAmount = 30;
private static int healthPotionDropChance = 20;
private static int manaPotionRecoveryAmount = 12;
private static int count = 0;
private static int count2 = 0;
private static int expUp = 0;
private static int level = 1;
public static void main(String[] args) {
SpellsAndAbilities spells = new SpellsAndAbilities();
Scanner in = new Scanner(System.in);
Random rand = new Random();
//String Array for enemies, more can be added, or taken away
String[] enemies = {"Skeleton", "Zombie", "Goblin", "Tiny Dragon", "Ben Afleck", "Little weird man", "Huge Bee", "Jeff", "Crazy Ray"};
//Set a variable running to true, to allow the program to run, so that if the user chooses to end the game early, they can do so
boolean running = true;
System.out.println("==================================================================");
System.out.println("Welcome to Mysterical World of Mysterical Things!");
System.out.println("Please press the number corresponding the action you wish to take.");
System.out.println("==================================================================");
//Clause to keep the game running with invalid inputs
GAME:
while(running) {
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\n\t### " + enemy + " has appeared! ###\n");
while (enemyHealth > 0) {
System.out.println("\tYour HP: " + health);
System.out.println("\tYour Mana: " + mana);
System.out.println("\t" + enemy + "'s HP: " + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Spells");
System.out.println("\t3. Use potion");
System.out.println("\t4. Run");
String input = in.nextLine();
if (input.equals("1")) {
int damageDealt = rand.nextInt(attackDmg);
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t>>> You hit the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> The " + enemy + " hit you for " + damageTaken + " damage <<<");
System.out.println();
if(health < 1) {
System.out.println("\t=== You died! ===");
break;
}
//
//Problem Starts Here
//
}else if (input.equals("2")) {
boolean set=true;
while(set) {
System.out.println("____________________________________________\n");
System.out.println("1. Fireblast (Cost: 6 mana, Damage: 10-19)");
System.out.println("2. Ice Sickle (Cost: 9 mana, Damage: 22-26)");
System.out.println("3. Whirlwind (Cost: 14 mana, Damage: 31-36)");
System.out.println("4. Earth shard (Cost: 28 mana, Damage: 38-42)");
System.out.println("5. Heal (Cost: 50 mana, Heals: 35 to 55 HP)");
System.out.println("6. Exit this menu");
System.out.println("____________________________________________");
int spellInput = in.nextInt();
switch (spellInput) {
case 1: if(mana >= 6) {
mana -= 6;
int damageDealt = spells.fireBlast();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Fire Blast!");
System.out.println("\t====================");
System.out.println("\n\t>>> Fireblast hits the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " damage<<<");
System.out.println();
break;
}
else {
break;
}
case 2: if (mana >= 9) {
mana -= 9;
int damageDealt = spells.iceSickle();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Ice Sickle!");
System.out.println("\t====================");
System.out.println("\n\t>>> Ice Sickle slashes the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
System.out.println("You need more mana");
break;
}
case 3: if(mana >= 14) {
mana -= 14;
int damageDealt = spells.whirlWind();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Whirlwind!");
System.out.println("\t====================");
System.out.println("\n\t>>> Whirlwind ravages " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
break;
}
case 4: if(mana >= 28) {
mana -= 28;
int damageDealt = spells.earthShard();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Earth Shard!");
System.out.println("\t====================");
System.out.println("\n\t>>> Earth shard pummels " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
break;
}
case 5: if(mana >= 50) {
mana -= 50;
health += spells.Heal();
int damageTaken = rand.nextInt(enemyAttackDmg);
health -= damageTaken;
System.out.println("\t===============");
System.out.println("\tYou cast Heal!");
System.out.println("\t===============");
System.out.println("\n\t>>> You recover " + spells.Heal() + " HP <<<");
System.out.println("\t>>> You took " + damageTaken+ " damage <<<");
System.out.println("\tYour HP: " + health);
System.out.println("\tYour Mana: " + mana);
System.out.println();
break;
}
else {
break;;
}
case 6: set = false;
default: break;
}
}
}
else if (input.equals("3")) {
if (numHealthPots > 0) {
count2++;
health += healthPotionHealAmount;
mana += manaPotionRecoveryAmount;
numHealthPots--;
System.out.println("\tYou drink a potion, healing for " + healthPotionHealAmount + " HP and recovering " + manaPotionRecoveryAmount + " mana" +
"\n\t>> You now have " + health + " HP and " + mana +" Mana <<" +
"\n\t>> You have " + numHealthPots + " potions left <<");
}
else {
System.out.println("\tYou have no potions left! Defeat enemies for a chance to get one!");
}
} else if (input.equals("4")) {
System.out.println("\tYou run away from the " + enemy + "!");
continue GAME;
}
else {
System.out.println("-------------------------------------");
}
}
if(health < 1) {
System.out.println("You pitifully limp out of the dungeon, too weak to go on!");
break;
}
count++;
System.out.println("=========================================");
System.out.println(" *** " + enemy +" was defeated! ***");
System.out.println("### You have " + health + " HP ### \n### And " + mana + " mana ###");
expUp += expUp + 25;
if (rand.nextInt(100) < healthPotionDropChance) {
numHealthPots++;
System.out.println(" # The " + enemy + " dropped a health potion");
System.out.println(" # You now have " + numHealthPots + " health potion(s) # ");
}
if(expUp > 99) {
level++;
health = health+22;
attackDmg = attackDmg + 2;
mana = mana + 7;
System.out.println("****** LEVEL UP!!! ******");
System.out.println("You are now level " + level + "!");
System.out.println("Each level up rewards 22 to total health, +2 to attack, and +7 to mana!");
}
System.out.println("=========================================");
System.out.println("What would you like to do now?");
System.out.println("Press 1 to continue fighting");
System.out.println("Pess 2 to exit");
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command");
input = in.nextLine();
}
if (input.equals("1")) {
System.out.println("You choose to continue, good luck!");
}
else if (input.equals("2")) {
System.out.println("You exit the game");
break;
}
}
System.out.println("####################");
System.out.println("Thanks for playing!");
System.out.println("####################");
System.out.println("Press 5 to see your score!");
String input2 = in.nextLine();
if (input2.equals("5")){
System.out.println("You defeated " + count + " enemies");
System.out.println("Max level achieved: " + level);
System.out.println("And you used " + count2 + " potions");
}
else {
System.out.println("Invalid input");
input2 = in.nextLine();
}
in.close();
}
}
Output ends up looking like this:
6. Exit this menu
____________________________________________
6
=========================================
*** Tiny Dragon was defeated! ***
### You have 136 HP ###
### And 6 mana ###
****** LEVEL UP!!! ******
I'm having an issue with exportation in Java. When I launch the JAR file I have created (in Eclipse), it instantly gives me an error, reading:
"Error: Invalid or corrupt jarfile C:\Users\Samuel\Desktop\Deep Dungeons.jar"
My Code is as follows:
import java.util.*;
public class Main {
public static void main(String[] args) {
// System Objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game variables
String[] enemies = {"Skeleton" , "Zombie", "Warrior", "Assassin"};
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;
// Player Variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 5;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
int enemiesKilled = 0;
int maxHealth = 100;
boolean running = true;
System.out.println("Welcome to the Dungeon!");
GAME:
while(running) {
System.out.println("--------------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + " has appeared! #\n");
while(enemyHealth > 0) {
System.out.println("\t Your HP: " + health);
System.out.println("\t " + enemy + "'s HP: " + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink health potion");
System.out.println("\t3. Run!");
String input = in.nextLine();
if(input.equals("1")) {
int damageDealt = rand.nextInt(attackDamage);
int damageTaken = rand.nextInt(enemyAttackDamage);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t> You strike the " + enemy + " for " + damageDealt + " damage");
System.out.println("\t> You recieve " + damageTaken + " in retaliation!");
if (health < 1) {
System.out.println("\t You have taken too much damage, you are to weak to go on!");
break;
}
} else if(input.equals("2")) {
if (numHealthPotions > 0) {
health += healthPotionHealAmount;
if (health > maxHealth)
health = 100;
numHealthPotions --;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP."
+ "\n\t> You now have " + numHealthPotions + "health potions left.\n");
} else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!\n");
}
} else if(input.equals("3")) {
System.out.println("\tYou run away from the " + enemy + "!");
continue GAME;
} else {
System.out.println("\nInvalid command!");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle.");
System.out.println("You killed " + enemiesKilled + ".");
break;
}
System.out.println("--------------------------------------");
System.out.println(" # " + enemy + " was defeated! # ");
enemiesKilled ++;
System.out.println(" # You have " + health + " HP left #");
if(rand.nextInt(100) > healthPotionDropChance) {
numHealthPotions ++;
System.out.println(" # The enemy dropped a health potion! # ");
System.out.println(" # You have " + numHealthPotions + " health potion(s). # ");
}
System.out.println("--------------------------------------");
System.out.println("What would you like to do now?");
System.out.println("1. Continue fighting");
System.out.println("2. Exit dungeon");
String input = in.nextLine();
while(!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command!");
input = in.nextLine();
}
if (input.equals("1")) {
System.out.println("You continue on your adventure!");
} else if(input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventures!");
System.out.println("You killed " + enemiesKilled + "!");
break;
}
}
System.out.println("######################");
System.out.println("# THANKS FOR PLAYING #");
System.out.println("######################");
}
}
I figured out the problem. When I was exporting, I should have been attempting to export as a runnable jar file, rather than a regular JAR file.
I have been trying to figure out how to make it so players could choose to restart the game at the end, but whenever I try to restart the loop, it says
Label Game was not found
even though it is clearly shown in this code.
// System objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assassin"};
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;
int enemyDeaths = 0;
List scores = new ArrayList();
// Player variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
boolean running = true;
System.out.println("Welcome to the Dungeon!");
Game:
while(running) {
System.out.println("-----------------------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + " has appeared! #\n");
while(enemyHealth > 0) {
System.out.println("\tYour HP: "+ health);
System.out.println("\t" + enemy + "'s HP:" + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink Health Potion");
System.out.println("\t3. Run");
String input = in.nextLine();
if(input.equals("1")) {
int damageDealt = rand.nextInt(attackDamage);
int damageTaken = rand.nextInt(enemyAttackDamage);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t> You strike the " + enemy + " for " + damageDealt + " damage. ");
System.out.println("\t> You received " + damageTaken + " in retaliation");
if(health < 1) {
System.out.println("\t> You have taken too much damage! You are too weak to go on!");
break;
}
}
else if(input.equals("2")) {
if(numHealthPotions > 0) {
health += healthPotionHealAmount;
numHealthPotions--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP"
+ "\n\t> You have " + numHealthPotions + " health potions left.\n");
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!");
}
}
else if(input.equals("3")) {
System.out.println("\tYou ran away from the " + enemy + "!");
continue Game;
}
else {
System.out.println("\tInvalid Command");
}
}
if(health < 1) {
System.out.println("You limp out of the dungeon, weak from battle");
break;
}
enemyDeaths++;
System.out.println("-----------------------------------------------");
System.out.println(" # " + enemy + " was defeated! #");
System.out.println(" # You have " + health + " HP left. #");
System.out.println(" # Your current score is " + enemyDeaths * 100 + " # ");
if(rand.nextInt(100) < healthPotionDropChance) {
numHealthPotions++;
System.out.println(" # The " + enemy + " dropped a health potion! #");
System.out.println(" # You have " + numHealthPotions + " health potion(s). # ");
}
System.out.println("-----------------------------------------------");
System.out.println("What would you like to do now?");
System.out.println("1. Continue fighting");
System.out.println("2. Exit Dungeon");
String input = in.nextLine();
while(!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid Command");
input = in.nextLine();
}
if (input.equals("1")) {
System.out.println("You continue on your adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventures!");
scores.add(enemyDeaths * 100);
break;
}
}
System.out.println("######################");
System.out.println("# THANKS FOR PLAYING #");
System.out.println("######################");
String randomWords;
in = new Scanner(System.in);
System.out.println("Enter a name to be remembered by");
randomWords = in.next();
scores.add(randomWords + " " + enemyDeaths * 100);
System.out.println(scores);
System.out.println("\n");
System.out.println("\n");
{
System.out.println("Would you like to play again?");
String input = in.nextLine();
if(input.equals("yes")) {
continue Game;
}
}
}
}
To keep it simple, you could just change the exit criteria:
if (!input.equals("yes")) {
break; // end the loop
}
Just a hint: it is considered a good practice to compare a literal against some variable:
if (!"yes".equals(input)) {
break; // end the loop
}
Doing the check this way will not fail with NullPointerException in case input is null, it just returns false in this case.
it's easier if you set the opposite:
if(input.equals("no")) running = false;
That way the while loop gets out cleanly and you don't need to use a cumbersome label to control your flow.
From
Branching Statements
The continue statement skips the current iteration of a for, while , or do-while loop.
You want to jump to the label 'Game' from outside of the labelled while loop,
which is not allowed.