I've been tasked to make a secret word guessing game and it is supposed to be game over and user is asked if they want to play again if the number of guesses for the character reaches 5.
I thought my incrementor is correct but perhaps not...
Here's the class:
public class SecretWord {
private String secretWord;
private String hintWord ;
private int numberOfTurns;
//Default Constructors
public SecretWord()
{
hintWord = "";
secretWord = "juice";
for (int i = 0; i < secretWord.length(); i++)
{
hintWord+="*";
}
this.numberOfTurns = 0;
}
//Accessors
public String getSecretWord()
{
return this.secretWord;
}
public String getHintWord()
{
return this.hintWord;
}
public int getNumberOfTurns()
{
return this.numberOfTurns;
}
//Mutators
public void setSecretWord ()
{
this.secretWord = "juice";
}
public void setHintWord ()
{
//Setting the hint word which sets the asterisks when you guess something right
char[] correctLetters = new char[secretWord.length()];
for (int i = 0; i<secretWord.length();i++)
{
hintWord+="*";
correctLetters[i] += '*';
}
}
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
//Methods
public void guessLetter(char guess)
{
String tempHintWord="";
for (int i = 0; i < secretWord.length(); i++)
{
if (secretWord.charAt(i) == guess)
{
tempHintWord += guess;
}
else
{
tempHintWord += hintWord.charAt(i);
}
}
hintWord = tempHintWord;
}
Here's the driver with my loops:
public class SecretWordGame {
//Constant for number of tries
public static final int NUM_TRIES = 5;
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Starts game
boolean quit = false;
while (quit == false)
{
System.out.println("Welcome to the word guessing game! You have " +
+NUM_TRIES+" tries to guess the secret word!");
SecretWord myWord = new SecretWord();
System.out.println("The current hint is \n"+myWord.getHintWord());
while (myWord.getNumberOfTurns() <=NUM_TRIES)
{
System.out.println("Guess a lowercase letter");
//Gets the first letter of what is entered
char tempGuess = keyboard.nextLine().charAt(0);
//Updates the hint by calling guess letter method
myWord.guessLetter(tempGuess);
System.out.println(myWord.getHintWord());
System.out.println("Guess the secret word");
String myGuess = keyboard.nextLine();
//Checks correct guess
if (myGuess.equals(myWord.getSecretWord()))
{
System.out.println("You win!");
break;
}
else
{
System.out.println("Keep trying!");
}
myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);
}
//Prompts user to play again
System.out.println("Game over! Try again?");
String userInput = keyboard.nextLine();
if(userInput.equalsIgnoreCase("no"))
{
quit = true;
}
else
{
System.out.println("Let's go again!");
}
}
System.out.println("Goodbye!");
}
Maybe the while loop (myWord.getNumberOfTurns() <=NUM_TRIES) comparison is wrong? Or perhaps the getNumberOfTurns incrementor is in the wrong place? I'm unsure.
change
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
to
public void setNumberOfTurns (int i)
{
this.numberOfTurns = i;
}
otherwise it would be set to 5 when this code is called myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);
Related
I want to ask the user if they want to play again when they finish a game. Currently, the only way for them to do that is to call the program again; however, I'd like to prompt the user for whether or not they'd like to play again once they finish a game.
public class Hangman
{
Random r;
GetData get;
String[] words = {"eat","what" };
String word;
boolean finished = false;
int badGuessCount=0;
boolean [] foundLetters;
String entryWord =" ";
public Hangman()
{
r = new Random();
get = new GetData();
playAGame();
}
public void playAGame()
{
word = words[r.nextInt(words.length)];
foundLetters = new boolean[word.length()];
while (!finished)
{
showGallows();
showWord();
getGuess();
checkGuess();
if (badGuessCount==6)
{
System.out.print('\u000C');
showGallows();
System.out.println("Sorry, but you lost.");
System.out.println("The word was: "+word);
finished=true;
}
}
}
public void showGallows()
{
System.out.print('\u000C');
if (badGuessCount==0)
man_0();
if (badGuessCount==1)
man_1();
if (badGuessCount==2)
man_2();
if (badGuessCount==3)
man_3();
if (badGuessCount==4)
man_4();
if (badGuessCount==5)
man_5();
if (badGuessCount==6)
completedMan();
System.out.println("\n");
}
public boolean showWord()
{
boolean goodGuess = false;
char ch = entryWord.charAt(0);
for (int lc=0; lc < word.length(); lc++)
if (foundLetters[lc]==true)
{
System.out.print(word.charAt(lc)+" ");
}
else if (word.charAt(lc)==ch)
{
System.out.print(word.charAt(lc)+" ");
foundLetters[lc] = true;
goodGuess = true;
}
else
System.out.print("_ ");
return goodGuess;
}
public void getGuess()
{
System.out.println("\n\n\nWhat letter do you want to guess?");
System.out.println("Type the whole word to guess the word.");
System.out.println("You have "+(6 - badGuessCount)+ "guess left.");
System.out.print("Enter guess");
entryWord = get.aWord();
}
public void checkGuess()
{
boolean goodGuess;
if (entryWord.length()>1)
{
if (entryWord.equals(word))
{
System.out.println("\n\nYes You won!");
finished = true;
System.out.println("close and run if you want to play again!");
String pause = get.aWord();
}
}
else
{
showGallows();
goodGuess = showWord();
if (goodGuess)
{
System.out.println("\n\n\nGood guess");
System.out.println("Press the Enter key to continue!");
String pause = get.aWord();
}
else
{
badGuessCount++;
System.out.println("\n\n\nBad guess!");
System.out.println("Press the Enter key to continue!");
String pause = get.aWord();
}
}
}
//public void completedMan()
}
How can I prompt the user to play again, and then restart the game based on their input?
You'll need to put playAGame(); itself inside a loop.
do
{
playAGame();
} while (UserWantsToKeepPlaying());
private boolean UserWantsToKeepPlaying() {
// Ask the user if they want to keep playing
}
I suggest a do - while loop because you'll always play the game at least once, and you (presumably) don't want to prompt the user to play again until after they finish playing a game.
error at while (UserWantsToKeepPlaying()); what I suppose to do
do
{
playAGame();
} while (UserWantsToKeepPlaying());
}
public boolean UserWantsToKeepPlaying(int number)
{
for (int i = 1; i > number; i--)
if (number % i == 0 && i != number) return false;
else return true;
System.out.print("\n\n Play Again 'No' Press 0 Yes' Press 1 : ");
}
I am writing a code that checks password entries. The main method checks a secondary method and outputs a line depending on whether it's true or false. My problem is when I compile it gives expected class error for the second method, but if I try to use the same class as my main it gives duplicate class error. I didn't think I needed a second class. Anyone care to help me out?
import java.util.Scanner;
public class CheckPassword {
public static void main(String[] args) {
scanner input = new Scanner(System.in);
System.out.println("Enter a password");
password = input.nextLine();
if (check(password)) {
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
}
public class CheckPassword {
public static boolean check(String password) {
boolean check = true;
if(password.length() < 8) {
check = false;
}
int num = 0;
for(int x = 0; x < password.length(); x++) {
if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
if(isDigit(password.charAt(x))){
num++;
if (num >=2){
check = true;
}
else{
check = false;
}
}
}
}
}
}
No need another class, but needed to static import isDigit and isLetter. I fixed your code:
import java.util.Scanner;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLetter;
public class CheckPassword {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a password");
String password = input.nextLine();
if (check(password)) {
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
public static boolean check(String password) {
boolean check = true;
if(password.length() < 8) {
check = false;
}
int num = 0;
for(int x = 0; x < password.length(); x++) {
if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
if(isDigit(password.charAt(x))){
num++;
if (num >=2){
check = true;
}
else{
check = false;
}
}
}
}
return check;
}
}
I am making basic java program to hold a secret word (mouse) and allow a user to guess letters. The program will end either when the user guesses all the letters in the word, or when they guess 7 wrong letters. Whenever I type any letter into the program, it will run through it without giving the user an option to enter another letter. What should I add so that it will only run the program once per letter entered? Also if it wasnt quite obvious I am new to coding.
import java.util.Scanner;
public class GuessWord
{
String Secretword="mouse";
String letter;
int index;
private int number;
private int counter;
private String guesses;
Scanner scan = new Scanner(System.in);
public GuessWord()
{
String Secretword="";
String letter = "";
String guesses = "";
int number = 0;
int counter = 0;
int index = 0;
}
public String getLetter(){
System.out.println("Please enter a letter");
letter = scan.next();
return letter;
}
public void calc(){
guesses=letter;
while(number <= 7 && counter<5)
{
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
guesses=guesses+" " +letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if(number == 7){
System.out.println("You lose");
}else
{
System.out.println("You win");
}
}
}//class
public class GuessWordR
{
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
g1.getLetter();
g1.calc();
}//class
}//main
You should use a while loop.
So while some condition is not met keep asking the user to enter a new key.
Perhaps add a new method to the GuessWord Class
public void startGuessing() {
while(hasGuesses /* some boolean flag */) {
getLetter()
getCalc()
}
}
And then call that method in your main method instead of getLetter() and getCalc().
You will need to add a boolean variable to your class to indicate when to exit this while loop and the logic to keep count of the number of failed guesses etc.
Use a boolean flag and run it in a loop. but for that you need to restructure your code as well. First fix the calc() method
public boolean calc() {
guesses = letter;
if (number <= 7 && counter < 5) {
if (Secretword.indexOf(letter) != -1) {
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
} else {
System.out.println("You entered an incorrect letter");
number++;
}
guesses = guesses + " " + letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if (number == 7) {
System.out.println("You lose");
return true;
} else if (counter == 5) {
System.out.println("You win");
return true;
} else {
return false;
}
}
Your main method should be update like this
public static void main(String[] args) {
GuessWord g1 = new GuessWord();
boolean completed = false;
while (!completed) {
g1.letter = g1.getLetter();
completed = g1.calc();
}
}
you ask user for input unless condition get satisfied instead of asking and calculating once. And read char by char input instead of reading whole string.
something like:
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
while(number <= 7 && counter<5){
g1.getLetter();
g1.calc();
}
}//class
I'm making a program of battleship with the user going against the computers random inputs choices in an 8x8 grid.
What I'm having trouble with is that I don't want my program to crash if my user inputs a String, such as "asdfklasdn", "h", etc... It doesn't crash if its an integer, such as 1,5,etc. Is there any way to change this without changing the rows and columns to strings? If I use try catch, it just gives me an error in the if-else statements right after in the userFire method.
Any help will be much appreciated. Thank you!
import java.util.*;
import java.util.Scanner;
public class Battleship
{
Scanner input = new Scanner(System.in);
public static final boolean DEBUG = false;
public static void breakln()
{
System.out.println("─────────────");
}
public static void createBoard(String [][]board)
{
for( int r = 0; r<board.length; r++)
{
for(int c= 0; c<board[0].length; c++)
{
board[r][c] = "-";
}
}
}
public static void showBoard(String[][] board)
{
breakln();
for(int r =0; r<board.length;r++)
{
if(DEBUG == true)
{
for(int c = 0; c<board[0].length;c++)
{
System.out.print(" " +board[r][c]);
}
System.out.println("");
}
else
{
for(int c = 0; c<board[0].length;c++)
{
if(board[r][c].equals("S"))
{
System.out.print(" " + "-");
}
else
{
System.out.print(" " + board[r][c]);
}
}
System.out.println("");
}
}
breakln();
}
public static void createShip(String[][] board, int size)
{
if(Math.random()<0.5)
{
int col = (int)(Math.random()*5);
int row = (int)(Math.random()*7);
for(int i = 0; i<size; i++)
{
board[row][col+i]="S";
}
}
else
{
int col = (int)(Math.random()*7);
int row = (int)(Math.random()*5);
for(int i = 0; i<size; i++)
{
board[row+i][col]="S";
}
}
}
public static int userFire(String[][] board, int hits, int torps)
{
Scanner input = new Scanner(System.in);
int row,col;
System.out.println("You have: " + torps + " torpedos");
System.out.println("Select row to fire in: ");
row = input.nextInt();
while(row>8||row<1)
{
System.out.println("Invalid. Enter a valid row (1-8)");
row = input.nextInt();
}
System.out.println("Select column to fire in: ");
col = input.nextInt();
while(col>8 || col<1)
{
System.out.println("Invalid. Enter a valid column (1-8)");
col = input.nextInt();
}
if(board[row-1][col-1].equals("S"))
{
hits++;
System.out.println("HIT ");
board[row-1][col-1] = "×";
}
else
{
System.out.println("MISS");
board[row-1][col-1] = "Ø";
}
return hits;
}
public static void endOfGame(int hits, int torps)
{
if(hits<4)
System.out.println(" LOSE ");
if(torps<1)
System.out.println("You have lost all your torpedos.");
else
if(hits>=4)
{
System.out.println("WINNER");
}
System.out.println("");
}
public static void main(String[] args)
{
System.out.println(" BATTLESHIP ");
System.out.println("");
String[][] board = new String[8][8];
createBoard(board);
createShip(board,4);
int torps = 25;
int hits = 0;
while(torps>0 && hits<4)
{
showBoard(board);
hits = userFire(board,hits,torps);
torps--;
}
endOfGame(hits, torps);
}
}
I've tried everyone's answers, but I received errors in this code.
if(board[row-1][col-1].equals("S"))
{
hits++;
System.out.println("╠══ HIT ══╣");
board[row-1][col-1] = "×";
}
else
{
System.out.println("╠══ MISS ══╣");
board[row-1][col-1] = "Ø";
}
return hits;
Add try/catch block inside row=input.nextInt() or every variable who receives input;
Here's sample code
try{
row = input.nextInt();
}
catch(Exception)
{
}
Just catch the exception, e.g.
try {
row = input.nextInt();
} catch (InputMismatchException e) {
System.err.println("Input is not an integer"); // or do some error handling
}
Try this out:
System.out.println("Invalid. Enter a valid row (1-8)");
String userInput = input.next();
try {
row = Integer.parseInt(userInput);
} catch (NumberFormatException exp) {
// Failed : Invalid input. Take actions if required.
// May be prompt user for correct input
}
You can use while(input.hasNextInt()) and println a message saying you only want ints?
Or a catch block as BroSlow said.
try {
xxx = input.nextInt();
} catch(NumberFormatException nfe) {
doXXXLoop();
}
// ....
public void doXXXLoop() {
System.out.println("Not a valid number. Enter another:");
try {
xxx = input.nextInt();
} catch(NumberFormatException nfe) {
doXXXLoop();
}
}
Unlike other code, this will easy repeat until a valid int is entered. Replace XXX with Row or Col or whatever you want.
I am supposed to write a program that will prompt the user to enter the hotel rooms that are occupied. Once that is done the user enters -1 and is prompted to enter a random hotel number. If the hotel room is occupied, it prints occupied. If the room is unoccupied, it printer unoccupied. I can't seem to figure out why the unoccupied won't print. Suggestions?
import java.util.Arrays;
import java.util.Scanner;
public class GoughAndreaChapter9
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int [] arr=new int[100];
int counter=0;
int currval=0;
System.out.println("Please enter an occupied hotel room number, -1 to quit ");
do
{
currval = sc.nextInt();
if(currval==-1)
break;
if(currval>0)
arr[counter++]=currval;
}
while(currval !=-1);
// sort using java API
int [] temparr=new int[counter];
for(int i = 0; i<counter; i++)
{
temparr[i] = arr[i];
}
arr = temparr;
Arrays.sort(arr);
//binary search.
int low=0;
int high = counter-1;
System.out.println("Please enter a room to search for: ");
currval = sc.nextInt();
int status=0;
int mid;
while(low<high)
{
if(arr[low]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[high]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
mid = low+high/2;
if(arr[mid]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[mid]<currval)
{
low=mid;
}
else if(arr[mid]<currval)
{
high = mid;
}
}
if(status==0)
System.out.println("Unoccupied");
}
}
Don't ofuscate! Do this:
Room.java
public class Room {
private boolean isOccupied;
public Room() {
this.isOccupied = false;
}
public boolean obtainTheRoom() {
if(!isOccupied) this.isOccupied = true;
return !isOccupied;
}
}
Main.java
import java.util.Scanner;
public final class Main {
private static final int ROOM_AMOUNT = 50;
private static int actualRoom;
private static Scanner cmdin = new Scanner(System.in);
public static void main(String[] args) {
Room[] rooms = new Room[ROOM_AMOUNT];
// Select some random, but static rooms to be occupied
for(int i = 1; i <= ROOM_AMOUNT; i++) {
if(i % 3 - 1 == 0 || i * 2 % i + 10 - 2 == 2) {
rooms[i - 1].obtainTheRoom();
}
}
for(;;) {
System.out.print("Enter a room number:\t");
try {
actualRoom = Integer.parseInt(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
if(rooms[actualRoom - 1].obtainTheRoom()) {
System.out.println("Got the room " + actualRoom + "! Now it's occupied -_-");
} else {
System.out.println("Room Occupied!");
}
}
}
private static void loopRoomNumber() {
System.out.print("That's not a valid room number!\n\n");
try {
actualRoom = Integer.parseInteger(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
}
}
That should work. Good luck!
I would change your last else if statements as follows. This will work. Because otherwise you will go in an endless loop;
else if (arr[mid] < currval)
{
low = mid;
--high;
}
else if (arr[mid] > currval)
{
high = mid;
++low;
}
Note that i have decremented the high when the mid value is less than the current value, and incremented the low value when the mid value is greater than the current value