Java hangman help, my code included - java

**Hello, I have to create a hangman game in java. I cant use arrays. Most of my code is done but I have been having some problems and some tips would be welcome.
I just found something else that I could use help on. After prompting the user for a new secret word and using newHangMan.setSecretWord(newWord); my disguised word does not reset to "????" (with the same number of "?" as words in the secret word).
I'm very sorry for such a long post and the bad formatting(1st time posting here).
Can anyone help?**
This is my class file:
public class HangMan
{
private String secretWord = "bigbang", disguisedWord = "";
private int guessCount = 0, missCount = 0;
public void setSecretWord(String newWord)
{
secretWord = newWord;
guessCount = 0;
missCount = 0;
int wordLength = newWord.length();
while(wordLength > 0)
{
disguisedWord = disguisedWord + "?";
wordLength--;
}
}
public String getSecretWord()
{
return secretWord;
}
public boolean isFound()
{
return secretWord.equalsIgnoreCase(disguisedWord);
}
public String getDisguisedWord()
{
return disguisedWord;
}
public int getGuessCount()
{
return guessCount;
}
public int getMissesCount()
{
return missCount;
}
public void guessCharacter(char c)
{
// int position = secretWord.indexOf(c);
boolean got_it = false;
String updateDisguised="";
for(int i=0; i < secretWord.length();i++)
{
if(c == secretWord.charAt(i))
{
updateDisguised = updateDisguised + secretWord.charAt(i);
String checkDuplicate = updateDisguised.substring(0,i);
int duplicatePos = checkDuplicate.indexOf(c);
if(duplicatePos <0)
guessCount++;
got_it = true;
}
else
{
updateDisguised = updateDisguised + disguisedWord.charAt(i);
}
}
if(got_it == false)
{
missCount++;
guessCount++;
}
disguisedWord = updateDisguised;
}
}
This is my main method:
import java.util.Scanner;
public class HangManGame {
public static void main(String[] args)
{
boolean retry= true;
String retry_ans;
Scanner kb = new Scanner(System.in);
HangMan newHangMan = new HangMan();
String word = newHangMan.getSecretWord();
String input;
char guess;
newHangMan.setSecretWord(word);
System.out.println("Hangman game starts:");
do{
System.out.println("Guess this: " + newHangMan.getDisguisedWord());
System.out.println("Enter your guess character: [guess]");
input = kb.next();
guess = input.charAt(0);
newHangMan.guessCharacter(guess);
System.out.println(newHangMan.getDisguisedWord());
System.out.println("Number of guesses so far : " + newHangMan.getGuessCount());
System.out.println("NUmber of misses so far: " + newHangMan.getMissesCount());
if((newHangMan.getMissesCount()==7) || (newHangMan.isFound()))
{
System.out.println("The game is over");
System.out.println("Would you like to try again?");
retry_ans = kb.next();
if(retry_ans.equalsIgnoreCase("yes"))
{
retry = true;
System.out.println("Please enter a new secret word:");
String newWord = kb.next();
newHangMan.setSecretWord(newWord);
}
else
{
retry =false;
}
}
} while(retry == true);
}
}

(newHangMan.isFound()=true)
should be
newHangMan.isFound()
Do not make an bool compare to another bool.
The = is evaluate the boolean.

Replace
while(retry = true);
with
while(retry);
The former is an assignment, so it never evaluates to false although it should.

Your while condition is an assignment, rather than a comparison, which is likely the cause of your problem - you're setting the value of retry to true (retry = true) rather than checking that the value of retry currently equals true (retry == true).

Classic java starter error. while check stetement should be
While(retry == true)

Related

Can't loop properly through list of objects

I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.

"team_name" cannot be resolved to a variable

I am having an unusual error with trying to return a string in my code. I am very new to java so I don't sometimes understand the ins and outs of how classes and returning values/assignment of values works. Any advice would be very helpful! Thank you :)
package videogaem;
import java.util.Scanner;
public class TeamName {
public String getTeamName() {
boolean valid_name = false;
Scanner reader = new Scanner(System.in);
while (valid_name == false) {
System.out.println("Enter team name here: ");
String team_name = reader.nextLine();
int name_length = team_name.length();
if (name_length >= 3 && name_length < 10) {
System.out.println(team_name + "... Sweet as name!");
valid_name = true;
return team_name;
}
else {
System.out.println("Name must be within 2 - 10 characters! :^)");
valid_name = false;
}
}
reader.close();
return team_name; /// <<< team_name is underlined red with the error
}
public static void main(String[] args) {
TeamName team = new TeamName();
team.getTeamName();
}
}
You need to declare the variable name outside the while condition. You have declared the variable name inside the while loop, so it's scope lies inside the while loop.Make sure the scanner is closed. In if statement you simply returning the team_name you have not closed the reader. It's opened, so first close the reader and then return the team_name.
import java.util.Scanner;
public class TeamName {
public String getTeamName() {
String team_name = null;
boolean valid_name = false;
Scanner reader = new Scanner(System.in);
while (valid_name == false) {
System.out.println("Enter team name here: ");
team_name = reader.nextLine();
int name_length = team_name.length();
if (name_length >= 3 && name_length < 10) {
System.out.println(team_name + "... Sweet as name!");
valid_name = true;
}
else {
System.out.println("Name must be within 2 - 10 characters! :^)");
valid_name = false;
}
}
reader.close();
return team_name;
}
public static void main(String[] args) {
TeamName team = new TeamName();
team.getTeamName();
}
}
in the getTeamName() method declear the String team_name ..
remove from the inner scope and right just before this scope.😊

Working with methods

I'm pretty new to coding Java. Below are codes for a program that is supposed to use several methods to ask for a string, reverse the string, test for palindrome and output the result of the test. I'm trying to debug my many errors.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original, String reverse) {
if (original.equals(getString(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String original, Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original,reverse);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
}
return reverse
}
public static void main(String[] args) {
System.out.print(promptForPalindrome);
}
}
For a start in main
you are calling
System.out.print(promptForPalindrome);
but if you look at the method promptForPalindrome you will see that it takes the parameters String original, Scanner Keyboard
BUT
These parameters are not even used, so maybe just delete them and change the main code to be
System.out.print(promptForPalindrome ());
Consider reading a basic java tutorial as well.
edit
Similar problems exist for isPalindrome - I suggest you change to
public static boolean isPalindrome(String original) {
return original.equals(getReverse(original));
}
and call it in as
boolean answer = isPalindrome(original);
But then your answer in
while (answer == false) {
will never change - so many bugs
The method signatures for the isPalindrome needs to be changed to only accept 1 string argument because you don't have the reversed string when it is called. Also there is no reason to pass in a scanner object for the prompt method because you instantiate it in the method. Also I changed your .equals to .equalsIgnoreCase so you don't get messed up by capitals. Also you need to update your boolean after each loop.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equalsIgnoreCase(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
answer = isPalindrome(original);
}
return getReverse(original);
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
Hope this helps I may have made some typos so let me know.
Your code has lot of errors. Check the below working code with comments in it.
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length() - 1; i > -1; i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) { // Two args are not required
// use equals if you need a case sensitive match
if (original.equalsIgnoreCase(getReverse(original))) { // Call getReverse() to reverse the string
return true;
} else {
return false;
}
}
public static String promptForPalindrome() { // Arguments are not required
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = null;
boolean answer = false;
do { // Use a do-while loop since you need to continue till it is success
original = keyboard.nextLine();
answer = isPalindrome(original);
if (!answer) {
System.out
.printf("Error: %s is not a palindrome. Please enter a palindrome.",
original);
}
} while (!answer);
keyboard.close(); // Close the Scanner
return original;
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
}
Thanks guys for all your help,
I was finally able to debug the code.
package osu.cse1223;
import java.util.Scanner;
public class Homework08a {
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equals(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String msg, Scanner keyboard) {
System.out.print(msg);
String userInput = keyboard.nextLine();
return userInput;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String msg ="Please enter a Palindrome";
String userInput = promptForPalindrome(msg, keyboard);
while (isPalindrome(userInput) == false) {
userInput = promptForPalindrome(msg, keyboard);
}
System.out.printf("%s is a palindrome", userInput);
}
}

Breaking out of a nested for loop without using break

My project is finally complete, but my only problem is that my teacher does not accept "breaks" in our code. Can someone help me resolve this issue, I have been working on it for days and I just can't seem to get the program to work without using them. The breaks are located in my DropYellowDisk and DropRedDisk methods. Other then that issue, my connect four program is flawless.
private static void DropYellowDisk(String[][] grid) {
int number = 0;
Scanner keyboard = new Scanner (System.in);
System.out.println("Drop a yellow disk at column (1–7): ");
int c = 2*keyboard.nextInt()+1;
for (int i=6;i>=0;i--)
{
if (grid[i][c] == " ")
{
grid[i][c] = "Y";
break;
}}
}
private static void DropRedDisk(String[][] grid) {
Scanner keyboard = new Scanner (System.in);
System.out.print("Drop a red disk at column (1–7): ");
int c = 2*keyboard.nextInt()+1;
for (int i =6;i>=0;i--)
{
if (grid[i][c] == " ")
{
grid[i][c] = "R";
break;
}
}}
my teacher does not accept "breaks"
From a programming standpoint, that's just plain silly (although I'm sure it has merit from an instructional one).
But there's an easy workaround in this particular case because the loops your breaking from are all at the end of their respective methods. As such, you can replace them with return statements. i.e:
private static void DropYellowDisk(String[][] grid) {
for (int i=6;i>=0;i--)
{
if (grid[i][c] == " ")
{
grid[i][c] = "Y";
return; //break
}}
}
boolean flag = false;
for (int i=6;i>=0 && !flag;i--) {
if (grid[i][c] == " ") {
grid[i][c] = "Y";
flag = true;
}
}
You can use boolean flag instead of break with while loop. Also you should compare strings by the equals method.
private static void DropYellowDisk(String[][] grid) {
int number = 0; boolean flag=true;
Scanner keyboard = new Scanner (System.in);
System.out.println("Drop a yellow disk at column (1–7): ");
int c = 2*keyboard.nextInt()+1;
int i=6;
while(i>=0&& flag)
{
if(grid[i][c].equals(" "))
{
grid[i][c]="Y";
flag=false;
}
i--;
}
}

Allowing a maximum number of times for system to accept incorrect PIN

I made a java login screen for a console application, but I need it to allow the user to input ther wrong PIN only 3 times. After the user has entered the PIN more than 3 times, the system should exit.
However, the loop which I used for the else part of the if condition does not seem to be making any changes to the program. (program wont execute the else part even once). Does anybody know what I am doing wrong?
if (userPIN.equals(a[0]))
{
System.out.println("You have login!");
valid=true;
String b=a[2];
Login.c=Double.parseDouble(b);
System.out.println(c);
obj.balance = Login.c;
obj.MainMenu();
System.exit(0);
}
else if(userPIN != a[0])
{
int count=0;
for(int i=0;i<count;i++)
{
System.out.println("Invalid PIN!");
check();
}
}
int count=0;
for(int i=0;i<count;i++)
The for loop's condition is initially false, hence it will never execute its body.
You have many problems in your code :
in the first if your using :
userPIN.equals(a[0])
but in the else you're using :
userPIN != a[0]
Your for loop cannot run correctly :
int count=0;
for(int i=0;i<count;i++)
Here is the correct implementation using Object-Orientation :
import java.util.Scanner;
public class PinChecker {
// Immutable Class
private static final class Pin {
private String _pin;
Pin(String pin) {
this._pin = pin;
}
public String toString() {
return _pin;
}
public boolean equals(Pin pin) {
if(pin.toString().equals(_pin)) {
return(true);
} else {
return(false);
}
}
}
public static final int NB_OF_TRIES = 3;
public static void main(String[] args) {
System.out.println("Enter your PIN :");
Pin userPin = new Pin("FOO");
Scanner console = new Scanner(System.in);
boolean pinMatch = false;
int i = 0;
while(!pinMatch && i < NB_OF_TRIES) {
Pin keyedPin = new Pin(console.nextLine());
i++;
if(userPin.equals(keyedPin)) {
pinMatch = true;
} else {
System.out.println("Invalid PIN!");
}
}
if(pinMatch) {
System.out.println("OK, nb of tries :" + i);
} else {
System.out.println("KO, nb of tries :" + i);
}
}
}
You can store the keyedPin object if you need to.
in the else part try !(userPIN.equals(a[0]))
Your else part is not checking the contents.

Categories

Resources