I am working on a rock paper scissors homework assignment for my java class. I am done with the program and I compiled it successfully. I ran the file and it looked like it was working. It gives me the menu and I choose a variable, R for example, and when I press enter it doesn't do anything but go to the next line. I press enter again and it gives me an index out of bounds error which I assume is because the second time it didn't have a variable to use. How do I get the program to move forward? The program is supposed to play five times then return a winner. Thanks in advance.This image is what I get when I run the program and press enter twice
package Rock;
import java.util.Scanner;
public class RPSG {
public static void main(String[] args) {
String[] computerHandArray = {"R","P","S"};
String computerHand ="", thisWinner="", theFinalWinner="";
int index=0;
int timesIWon=0;
int timesComputerWon=0;
Scanner in = new Scanner(System.in);
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\nEnter Your Hand (R, P, or S): ");
for (int i=0; i<5; i++) {
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
}
else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
}
}
if(timesIWon == timesComputerWon)
theFinalWinner = "TIE";
else if(timesIWon > timesComputerWon)
theFinalWinner = "ME";
else if(timesComputerWon > timesIWon)
theFinalWinner = "COMPUTER";
System.out.println("I won :" + timesIWon);
System.out.println("I won :" + timesComputerWon);
System.out.println("The Final Winner after 5 games is:" +theFinalWinner);
}
private static String theWinnerofOneGame(String myHand, String computerHand){
String theWinner = "Tie";
if(myHand.equals(computerHand)) {
theWinner = "Tie";
}
else if(myHand.equals("R")) {
if (computerHand.equals("P")) {
theWinner = "COMPUTER";
}
}
else if(computerHand.equals("S")) {
theWinner = "ME";
}
else if(myHand.equals("P")) {
if (computerHand.equals("R")) {
theWinner = "ME";
}
else if(computerHand.equals("S")) {
theWinner = "COMPUTER";
}
}
else if(myHand.equals("S")) {
if (computerHand.equals("R")) {
theWinner = "COMPUTER";
}
else if(computerHand.equals("P")) {
theWinner = "ME";
}
}
return theWinner;
}
}
You print the prompt for input only once, i.e. before the for loop. Now when you enter your first input, the content of the loop will be executed. Because you don't print anything inside the loop, there is no prompt for the next round. After you press enter a second time, the in.nextLine() returns an empty string and subsequently, the substring method throws the exception.
You should probably do something like this (note the marked lines):
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\n");
for (int i=0; i<5; i++) {
> System.out.println("Enter Your Hand (R, P, or S): ");
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
> System.out.println("You won.");
} else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
> System.out.println("The computer won.");
}
}
And even better, check if the input of the user is valid before computing the substring.
I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}
If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)
You should use
while (!play)
instead of
while (play = false)
When the code runs and you ask for char and type a letter lets say 'e' the output makes it "eeeee" instead of filling in the e's in the partial word method. I'm not sure how to fix it. I think the problem is either in replaceChar method or the updatePartialWord method. Would love some help. Thanks!
P.S i need to keep the method inputs the same even if there is an easier way!
// creates partialWord using string length then creating a new string with the same amount of dashes
public static String createPartialWord(String secretWord)
{
String newsecretWord = "";
int wordLength = secretWord.length();
while (wordLength > 0)
{
newsecretWord = newsecretWord + "-";
//System.out.print("-");
wordLength--;
}
System.out.println();
return newsecretWord;
}
//replaces character at certain ints
public static String replaceChar(String word, char c, int i)
{
//return word.replace(word.charAt(i), c);
String newText = word.replace(word.charAt(i), c);
return newText;
}
public static String updatePartialWord(String partial, String secret, char c)
{
if(c==secret.charAt(0))
{
return replaceChar(partial, c, 0);
}
if(c==secret.charAt(1))
{
return replaceChar(partial, c, 1);
}
if(c==secret.charAt(2))
{
return replaceChar(partial, c, 2);
}
if(c==secret.charAt(3))
{
return replaceChar(partial, c, 3);
}
if(c==secret.charAt(4))
{
return replaceChar(partial, c, 4);
}
return partial;
}
//Prints hangman
public static void printHangman(int guessLeft)
{
String HEAD = " ";
String BODY = " ";
String LEGS = " ";
String LEFTARM = " ";
String RIGHTARM = " ";
System.out.println("_____");
System.out.println("| |");
if (guessLeft < 6) {
HEAD = "()";
}
System.out.println("| " + HEAD);
if (guessLeft < 5) {
BODY = "||";
}
if (guessLeft < 4) {
LEFTARM = "\\";
}
if (guessLeft < 3) {
RIGHTARM = "/";
}
System.out.println("| " + LEFTARM + BODY + RIGHTARM);
if (guessLeft < 2) {
LEGS = "/";
}
if (guessLeft < 1) {
LEGS += "\\";
}
System.out.println("| " + LEGS);
System.out.println("|_____\n\n\n\n");
}
public static String generateSecretWord()
{
String[] names = { "alone", "apple", "anode", "abuse", "angle", "amaze","adobe","amuse",
"avoid","peter","sound","doubt","upper","lower","layer","enter","alter","boxer",
"faced", "alive","adore","names","voice","water","plate","pepsi","pizza","paste",
"hello","sugar","money","paper","while","times", "mouth","other","agile","again",
"acute","arise","argue","ankle","badge","blaze","bride","chase","sense","craze",
"dance","false","exile","drove"};
String name = names[(int) (Math.random() * names.length)];
return name;
}
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
String secretWord = generateSecretWord();
String partialWord = createPartialWord(secretWord);
System.out.println(" Welcome to HangMan");
System.out.println("I picked a secret word");
System.out.println();
//start for statement for main game
System.out.println("The current Partial Word is: " + partialWord);
for(int i = 6;i>0;)
{
System.out.println("The current Hangman picture is");
printHangman(i);
System.out.println("Player 2, you have " + i + " remaining guesses");
System.out.println("Would you like to guess the secret work or guess a character?");
System.out.println("Type \"word\" for word, type \"char\" for character");
String playerInput = stdin.nextLine();
String charInput = "char";
String wordInput = "word";
if(playerInput.equals(charInput))
{
System.out.println("Please type a character");
char input = stdin.nextLine().charAt(0);
if(secretWord.charAt(0)== input || secretWord.charAt(1)== input || secretWord.charAt(2)== input ||
secretWord.charAt(3)== input || secretWord.charAt(4)== input)
{
System.out.println("That character is in the secret word");
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
}
else
{
System.out.println("Sorry that charcater is not in the secret word");
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
if(i==1)
{
System.out.println("You've killed the hangman. You've lost the game");
printHangman(0);
break;
}
i--;
}
}
else
{
System.out.println("Please guess the word");
String userGuess = stdin.nextLine();
if(userGuess.equals(secretWord))
{
System.out.print("Congrats that is the secret word! You've won the game!");
System.out.println("Here is the hangman");
printHangman(i);
break;
}
else
{
System.out.println("Sorry thats not the secret word. You've lost.");
break;
}
}
}
}
}
public static String replaceChar(String word, char c, int i) {
String newText = word.replace(word.charAt(i), c);
:
The word in this case is -----, so you are replacing all occurrences of the character at position i (which is -) with the letter.
So all - characters are becoming the character you just entered.
You should instead be changing each character in the partial word, if and only if the equivalent character in your secret word matches the character just entered, something like:
public static String replaceChar(String word, String secret, char c) {
for (int i = 0; i < word.length(); i++) {
if (secret.charAt(i) == c) {
word = word.substring(0, i) + c + word.substring(i+1);
}
}
return word;
}
Of course, since you're now using the secret word and the position of the character is irrelevant, you change what gets passed in. The calling code can be modified to be:
if (c == secret.charAt(0))
return replaceChar(partial, secret, c);
if (c == secret.charAt(1))
return replaceChar(partial, secret, c);
// :
// and so on.
Of course, even with that fix, you still have a problem:
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
This outputs the new partial word as calculated by the function but it doesn't actually change the partial word. You need something along the lines of:
partialWord = updatePartialWord(partialWord, secretWord, input));
System.out.println("The current partial word is: " + partialWord);
As per the javadocs
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
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 am trying to make a text-based Hangman in Java.
This is my Java code:
package hangman;
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class Hangman {
public static void main(String[] args) {
// TODO code application logic here
Scanner chez = new Scanner(System.in);
Scanner waffle = new Scanner(System.in);
Random randomGenerator = new Random();
StringBuilder displayWord = new StringBuilder("______________________________");
String theWord = null;
String preLetter;
//String sbDisplayWord;
char letter = 0;
int randomNumber;
int lengthOfWord;
int numberOfLetterInWord = 0;
int gDisplay;
int guessWordNumber = 0;
String guessWord;
RandomWord troll = new RandomWord();
randomNumber = randomGenerator.nextInt(12);
//Fill var with the word.
theWord = troll.wordDecide(randomNumber);
System.out.println ("Welcome to Hangman!");
lengthOfWord=theWord.length( );
System.out.println("This word has " + lengthOfWord + " letters.");
System.out.println("You have 20 guesses.");
for (int g =19; g >= 0; g--) {
System.out.println("If you want to guess the word, type 0. If you want to guess a letter, type 1.");
guessWordNumber=chez.nextInt();
if (guessWordNumber==0) {
System.out.println("Enter the word now. Remember, don't capitalize it.");
guessWord=waffle.nextLine();
if (guessWord.equals(theWord)) {
System.out.println("YOU WIN");
System.exit(0);
} else {
System.out.println("Sorry, this wasn't the correct word.");
}
} else if (guessWordNumber==1) {
System.out.println("Please enter the letter you wish to guess with.");
//System.out.println("It will tell you if you have guessed right for any of the letters. If it is blank, that means none of the letters match.");
preLetter=chez.nextLine();
letter=preLetter.charAt(0);
System.out.println("");
for(int i = 0; i <= lengthOfWord -1; i++ ) { //-Eshan
if (letter == theWord.charAt( i )) {
numberOfLetterInWord=i+1;
System.out.println("This letter matches with letter number " + numberOfLetterInWord + " in the word.");
displayWord.setCharAt(i, letter);
} else {
numberOfLetterInWord=i+1;
System.out.println("This letter doesn't match with letter number " + numberOfLetterInWord + " in the word.");
}
}
System.out.println("");
System.out.println("The word so far is " + displayWord);
System.out.println("");
gDisplay = g + 1;
System.out.println("You have " + gDisplay + " guesses left.");
} else {
System.exit(0);
}
}
System.out.println("GAME OVER");
System.exit(0);
}
}
package hangman;
public class RandomWord {
private static String[] wordArray = {
"psychology",
"keratin",
"nostalgia",
"pyromaniac",
"chlorophyl",
"derivative",
"unitard",
"pterodactyl",
"xylophone",
"excommunicate",
"obituary",
"infinitesimal",
"concupiscent",
};
public String wordDecide(int randomNumber) {
String theWord;
theWord = wordArray[randomNumber];
return theWord;
}
}
Netbeans is giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at hangman.Hangman.main(Hangman.java:56)
Java Result: 1
This is probably happening when you call charAt(0) on a string of length 0. You should check to see that the string is not empty before calling the method.
You are getting a StringIndexOutOfBoundsException due to the fact the line
guessWordNumber = chez.nextInt();
does not consume newline characters and passes the character through to the line
preLetter = chez.nextLine();
which then doesn't block as it will have already received input. This assigns an empty String to preLetter resulting in the exception. You can use Scanner#nextLine to consume this character:
guessWordNumber = Integer.parseInt(chez.nextLine());