Pulling multiple elements out of an array and labeling them specifically - java

I need to program an array that functions as horses in a race. Everytime the user presses enter the horses will "run" or the array will add random numbers to them and update their position. The console is printing their position after every button press. I need to label the 1st 2nd and 3rd horses after the race is over (when the horses hit 15). I cannot figure out how to do this.
Right now I am searching through the array and if an element of the array is greater than or equal to 15 I have it set to print the first place horse. How do I make it so that it will print the 2nd and 3rd place as the next highest positions (ex. 1st = 15, 2nd = 13, 3rd = 12)?
Also, it appears that my program will not stop. How do I get it to stop after 15 or higher is reached? Thank you!
import java.util.*;
public class HorseRace2{
public static void main(String[ ] arg){
Scanner reader = new Scanner(System.in);
int range = 3;
int win = 15;
final int SIZE = 3;
Random ran = new Random( );
boolean winner = false;
int[ ] arrRan = new int[SIZE];
System.out.print("Off to the races! Press enter to make the horses run.");
String readString = reader.nextLine();
while(readString!=null){
System.out.print(readString);
if(readString.equals("")){
for(int i = 0; i<arrRan.length; i++){
arrRan[i] = arrRan[i] + (ran.nextInt(3) + 1);
System.out.println("Horse " + (i+1) + ":" + arrRan[i]);
}
}//end if
if(reader.hasNextLine()){
readString = reader.nextLine();
System.out.println("Please press enter to make the horses run.");
}
for(int i = 0; i<arrRan.length; i++){
if(arrRan[i]>=win){
System.out.println("1st place: Horse " + (i+1));
}
}
}//end while
}//close main
}//close class

It's not stopping because the condition readString != null isn't being violated.
For it to print the non-1st place horses, sort the array and assign places as applicable.
For it to stop, try replacing while( readString != null ) with while( nobodyHasWon ). Make a boolean boolean nobodyHasWon = true and set it to false when a horse has won (i.e., after System.out.println("1st place: Horse " + (i+1));).
Alternatively, you could do this:
// assumptions made: there is only one winner at 15, the rest are below 15, there are no ties, and the first ranked horse has been found
int second, third, secondValue, thirdValue;
secondValue = 0; thirdValue = 0;
for( int i = 0; i < arrRan.length; i++ ) {
if( i != <indexOfFirstPlaceHorse> )
{
if( arrRan[ i ] > secondValue ) {
second = i;
secondValue = arrRan[ i ];
}
}
}
for( int i = 0; i < arrRan.length; i++ ) {
if( i != <indexOfFirstPlaceHorse> && i != second ) {
if( arrRan[ i ] > thirdValue ) {
third = i;
thirdValue = arrRan[ i ];
}
}
}

Try this one I updated the code.
SEE DEMO
Scanner reader = new Scanner(System.in);
int range = 3;
int win = 15;
final int SIZE = 3;
Random ran = new Random( );
boolean winner = false;
int[ ] arrRan = new int[SIZE];
System.out.print("Off to the races! Press enter to make the horses run.");
String readString = reader.nextLine();
while(readString!=null){
if(!winner){
System.out.print(readString);
if(readString.equals("")){
for(int i = 0; i<arrRan.length; i++){
arrRan[i] = arrRan[i] + (ran.nextInt(3) + 1);
System.out.println("Horse " + (i+1) + ":" + arrRan[i]);
}
}//end if
for(int j = 0; j<arrRan.length; j++){
if(arrRan[j]>=win){
winner =true;
}
}
if(reader.hasNextLine()){
readString = reader.nextLine();
System.out.println("Please press enter to make the horses run.");
}
}else{
int[] arrClone = new int[arrRan.length];
for(int i=0;i<arrRan.length;i++){
arrClone[i] = arrRan[i];
}
arrRan = sortArray(arrRan);
int[] arrRank = new int[arrRan.length];
int prevNum = arrRan.length;
for(int i=0;i<arrRan.length;i++){
boolean flag = true;
for(int j=0;j<arrRan.length;j++){
if(arrRan[i]==arrClone[j]){
if(j!=prevNum && flag){
prevNum = j;
arrRank[i] = j+1;
flag=false;
}
}
}
}
System.out.println("1st place: Horse " + (arrRank[0]));
System.out.println("2nd place: Horse " + (arrRank[1]));
System.out.println("3rd place: Horse " + (arrRank[2]));
break;
}
}//end while
}
public static int[] sortArray (int[] inArray)
{
//Construct the array we're using here
int[] newArray = inArray;
for(int x = 0; x < newArray.length; x++) //a.length = # of indices in the array
{
for(int y = 0; y < newArray.length; y++)
{
if(newArray[x] > newArray [y]) {
int tempValue = newArray[y];
newArray[y] = newArray[x];
newArray[x] = tempValue;
}
}
}
return newArray;
}

Related

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Trouble assigning a variable to display the index of an array

I am writing a program where I generate 100 random numbers, I prompt the user to enter a number, and the program says the number was found at index XX. Or that the number was not found. Here is what I have:
import java.util.*;
import java.util.Random;
public class lab1
{
public static void main (String[]args)
{
//Let's create an array with 100 random numbers
int [] randomArray = new int [100];
Random randomGenerator = new Random();
for(int i = 0; i < randomArray.length; i++)
{
randomArray[i] = randomGenerator.nextInt(100) + 1;
}
//ask user to enter a number between 1 and 100
Scanner input = new Scanner(System.in);
int searchNumber;
System.out.println("Please enter a number between 1 and 100 to search
for: ");
searchNumber = input.nextInt();
boolean found = false;
for(int i = 0; i < randomArray.length; i++)
{
if(searchNumber == randomArray[i])
{
found = true;
break;//Exits the loop
}
}
if(found)
{
System.out.println("We have found your number, " + searchNumber + "
at index " + index);
}
else
{
System.out.println("We did not find your number");
}
}
}
I am not able to get the index to display when my program finds a number, I know this is because the variable "i" is only defined within the for loop. I am not sure how to create a new variable outside of the for loop and assign i to that variable inside the for loop.
declare i outside the loop i.e.
int i;
for(i = 0; i < randomArray.length; i++)
{
...
...
...
}
then you can use the index i within your println.
if(found)
{
System.out.println("We have found your number, " + searchNumber + "at index " + i);
}
else
{
System.out.println("We did not find your number");
}
You had the right idea all along, and even articulated it perfectly: "...create a new variable outside of the for loop and assign i to that variable inside the for loop":
int foundAt = -1;
for(int i = 0; i < randomArray.length; i++)
{
if(searchNumber == randomArray[i])
{
foundAt = i;
break;//Exits the loop
}
}
if(foundAt != -1)
{
System.out.println("We have found your number, " + searchNumber + "
at index " + foundAt);
}
else
{
System.out.println("We did not find your number");
}
}

How to scramble a word that is picked randomly from a text file

I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code

How to store user input for continued use?

How can I repeat this program but keep the user input when it is displayed to them a second time or the third time etc. The program asks them where they want to sit, then the display shows them an X in place of where they said. I want the X to stay for the next time it asks for their input until the user decides to quit the program by choosing "2".
import java.util.Scanner;
import java.util.Arrays;
class AirplaneSeating {
static Scanner inNum = new Scanner(System.in);
static Scanner inStr = new Scanner(System.in);
static void option() {
String[][] seatingChart = new String[10][4];
int rows = 10;
int columns = 4;
seatingChart = new String[rows][columns];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
seatingChart[i][j] = "" + ((char)('A' + i)) + ((char)('1' + j));
}
}
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
System.out.print(seatingChart[i][j] + " ");
}
System.out.println("");
}
System.out.println("What seat would you like to reserve? ");
String str = inStr.nextLine();
System.out.println("You chose: " + str);
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
if(seatingChart[i][j].equals(str)) {
System.out.print("X" + " ");
} else {
System.out.print(seatingChart[i][j] + " ");
}
}
System.out.println("");
}
}
public static void main(String[] args) {
int choice;
do {
System.out.println("Choose from one of the following options:");
System.out.println("\tl. Choose a seat to reserve: ");
System.out.println("\t2. Quit");
System.out.print("Enter 1 or 2: ");
choice = inNum.nextInt();
switch(choice) {
case 1:
option();
break;
case 2:
System.out.println("\nGoodbye!");
break;
default:
System.out.println(choice + " is not an option. Please choose 1, 2, 3, 4, or 5.");
}
}while(choice !=2);
}
}
Use BufferedReaders,BufferedWriters and a .txt file. They're pretty simple to use and allow you to save something in a text document which can later be accessed to reload previous information.

Hangman wrong guesses not printing correctly

I have this Hangman program that i am working on for school and i cant get the number of wrong guesses to print correctly when the user guesses a wrong letter. Here is my code that i got so far, i would appreciate any tips.
import java.util.Scanner;
public class HangmanTest {
public static void main(String[] args) {
String[] wordBank = { "madelynn", "crystal", "mcbride", "daughter",
"adorable", "beautiful", "andrew", "programming", "alyssa",
"computers", "mcbreezy", "maddy", "happy", "vacation", "beach",
"java", "benefical", "military", "veteran", "standale",
"lions", "tigers", "redwings", "pistons", "michigan",
"football", "baseball", "hockey", "basketball", "golf" };
int minimum = 0;
int maximum = wordBank.length - 1;
String again;
do {
int choice = minimum + (int) (Math.random() * maximum);
String word = wordBank[choice];
// Converts the random word to asterix
String userWord = "";
for (int i = 0; i < word.length(); i++) {
userWord += "*";
}
// Breaks into a bunch of characters
char[] userWordCh = userWord.toCharArray();
// Show the random word
System.out.println("The word for you to guess is " + userWord);
// instantiate a scanner object
Scanner input = new Scanner(System.in);
int size = word.length();
int rightGuesses = 0;
int wrongGuesses = 0;
while (size != rightGuesses) {
System.out.println("Enter a character: ");
String response = input.next();
char ch = response.charAt(0);
char[] wordChars = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
System.out.print("The word is: ");
for (int j = 0; j < userWordCh.length; j++)
System.out.print(userWordCh[j]);
System.out.println();
} // end of while loop
System.out.println("You had " + wrongGuesses + " wrong guesses.");
System.out.println("Would you like to play again y/n: ");
again = input.next();
} while (again.equals("y"));
}
}
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
In this loop, you increment rightGuesses by 1 every time the guess matches a letter in the word, and wrongGueeses by 1 every time the guess does not match a letter in the word. As you can imagine, this will lead to the numbers, collectively, being incremented by the same number as the number of letters, when it should only be incremented once.
Try something like:
boolean foundMatch = false;
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
if (!foundMatch)
{
++rightGuesses;
foundMatch = true;
}
}
}
if (!foundMatch)
{
++wrongGuesses;
}
// end of for loop
Now we only increment one of rightGuesses and wrongGuesses once - rightGuesses can only be incremented if we have not found a match (setting found match to true), and wrongGuesses can only be incremented once if we have not found a match.
problem is in your for loop. You are iterating over each letter, and for every letter that doesn't match yours, you mark it as an incorrect guess. It should only be marked incorrect if NONE of the letters are correct. Additionally it should only be marked right if you haven't marked it already.
import java.util.Scanner;
import java.util.ArrayList;
public class HangmanTest {
public static void main(String[] args) {
String[] wordBank = { "madelynn", "crystal", "mcbride", "daughter",
"adorable", "beautiful", "andrew", "programming", "alyssa",
"computers", "mcbreezy", "maddy", "happy", "vacation", "beach",
"java", "benefical", "military", "veteran", "standale",
"lions", "tigers", "redwings", "pistons", "michigan",
"football", "baseball", "hockey", "basketball", "golf" };
int minimum = 0;
int maximum = wordBank.length - 1;
String again;
do {
int choice = minimum + (int) (Math.random() * maximum);
String word = wordBank[choice];
// Converts the random word to asterix
String userWord = "";
for (int i = 0; i < word.length(); i++) {
userWord += "*";
}
String guessedLetters="";
// Breaks into a bunch of characters
char[] userWordCh = userWord.toCharArray();
// Show the random word
System.out.println("The word for you to guess is " + userWord);
// instantiate a scanner object
Scanner input = new Scanner(System.in);
int size = word.length();
int rightGuesses = 0;
int wrongGuesses = 0;
boolean foundLetter;
char[] wordChars = word.toCharArray();
guessLoop:
while (size != rightGuesses) {
System.out.println("Enter a character: ");
String response = input.next();
char ch = response.charAt(0);
foundLetter=false;
for (int i=0;i<guessedLetters.size();i++){
if (ch == guessedLetters.charAt(i)){
System.out.println("Already guessed that letter!");
continue guessLoop;
}
}
guessedLetters+=response;
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
foundLetter=true;
userWordCh[i] = ch;
++rightGuesses;
}
} // end of for loop
if(!foundLetter)
++wrongGuesses;
System.out.print("The word is: ");
for (int j = 0; j < userWordCh.length; j++)
System.out.print(userWordCh[j]);
System.out.println();
} // end of while loop
System.out.println("You had " + wrongGuesses + " wrong guesses.");
System.out.println("Would you like to play again y/n: ");
again = input.next();
} while (again.equals("y"));
}
}
I'm guessing here, but I think this might be wrong:
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
This will increment the rightGuesses and wrongGuesses variables for each character in the word that matches/doesn't match the inputted character. Instead, you need to set a flag when a character "matches", then check that flag at the end to update rightGuesses and wrongGuesses.
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
This for loop is causing your problem with wrong guesses, since it will say that a character is a wrong guess even though it is in the word. An option you can do is have some boolean that is switched to true when it finds the letter. That way, when you leave the for loop, you check to see if that value is true. If it isn't, increment the wrong guesses.

Categories