I am trying to write a code to play hangman and it is working correctly but every time when I input a character, it resets my output. Can someone please help.
my code:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i++){
ask = ask + "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (char i : word.toCharArray()){
if(input == i){
System.out.print(input);
continue;
}
System.out.print("_");
}
}
}
}
A small piece of the output:
______
hint: It is a fruit
Enter a character:
a
__a___
Enter a character:
o
o_____
Enter a character:
r
_r____
Enter a character:
n
___n__
Enter a character:
When I enter 'a' it prints it correctly but when I enter some other character it prints that character an not 'a'. Can somebody pls tell me what should I do to get the correct output.
It looks like you are not saving the string with the character added to the game, you are only printing it. You will probably want to do something like add the new character to the string variable _ask rather than printing as you go, then print after the for loop has run. Basically you are not storing the past rounds anywhere.
As mentioned in the other answer you need to remember the characters from previous attempts. This could for example be done like this:
String tempAsk = "";
for (char i : word.toCharArray()){
if(input == i){
tempAsk += i;
} else {
tempAsk += ask.charAt(i);
}
}
ask = tempAsk;
System.out.println(ask);
I think that,
In the loop for (char i : word.toCharArray()),
you should add the character to ask (or have another string variable named ans),
and then print ask at the end of the loop
because you are not updating the value of ask and printing the place of the character in the string,
and when the loop runs a second time it doesn't show the last character that u entered
plus you can have specific hints according to the fruit name using switch case
and maybe have an error pop up when the player enters the wrong character
You can use a character array to check what letters are present so far like so:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
// Create a character array to store the result so far
char[] result = new char[word.length()];
//Fill the array with _
Arrays.fill(result, '_');
System.out.println(new String(result));
System.out.println("hint: It is a fruit");
int numChances = 15;
for (int j = 1; j <= numChances; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (int i = 0; i < word.length(); i++) {
if(word.charAt(i) == input){
//update the array with user's correct response
result[i] = input;
}
}
// Check how we're doing so far. Make a string with the result
String untilNow = new String(result);
// Show user what we have so far
System.out.println(untilNow);
//Check if the user has guessed the word.
if(untilNow.equalsIgnoreCase(word)) {
System.out.println("You win...");
break;
}
}
}
Related
The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}
For example lets say you have the string "greg". The program prompts you to enter which character to remove and you say "g", the program then prompts "Enter the g you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.)" and you enter "2". The program then outputs the new sentence which is "gre". This is a piece of my program for my CSCI class and I know how to do it using replace(), but my professors says we can only use loops and these string methods length, concat, +, charAt, substring, and equals (or equalsIgnoreCase). I can't seem to figure it out any help would be appreciated. Thank you!
As pointed out in comments, you need to maintain count for number of occurrences and build a new string skipping nth occurence(Strings are immutable in Java):
public static String removeNthCharacter(String input, char ch, int occurence) {
StringBuilder sb = new StringBuilder();
int totalOccurences = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch) {
totalOccurences++;
if (totalOccurences == occurence) {
// Skip This character
continue;
}
}
sb.append(input.charAt(i));
}
return sb.toString();
}
I tested this and it seems to generate expected output:
public static void main(String[] args) {
System.out.println(removeNthCharacter("greg", 'g', 2));
System.out.println(removeNthCharacter("greggggeegeegggg", 'g', 6));
}
This produces this output:
src : $ java RemoveChar
gre
greggggeeeegggg
public static void main(String[] args) {
System.out.print("Enter a String : ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.print("Enter character to be removed : ");
scanner = new Scanner(System.in);
char character = scanner.next().charAt(0);
System.out.println("Possible positions of "+character+" : ");
// find all occurrences forward
for (int i = -1; (i = input.indexOf(character, i + 1)) != -1; i++) {
System.out.println(i);
}
System.out.print("Select any above index to remove : ");
scanner = new Scanner(System.in);
int index = scanner.nextInt();
System.out.println("Result : "+input.substring(0, index)+input.substring(index+1, input.length()));
}
output
Enter a String : greg
Enter character to be removed : g
Possible positions of g :
0
3
Select any above index to remove : 0
Result : reg
output
Enter a String : greg
Enter character to be removed : g
Possible positions of g :
0
3
Select any above index to remove : 3
Result : gre
I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers
This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}
I have been working on my hangman program for far to long and cannot figure out why it is not replacing the characters entered with the asterisks.
There are a lot of details I have not added so please do not sit here and judge that. I need someone to tell my why the character the user enters is not replacing the asterisks and If you know what I could do to fix it please tell me.
I'm struggling. I have edited my program to show you where I know the logic error is coming from however I do not know what the error is.
String hiddenWord = wordList[rand];
char[] asterisks = new char[MAXCHAR];
hideWord(hiddenWord);
System.out.println(Arrays.toString(hideWord(hiddenWord)));
numGuess( hiddenWord,asterisks);
public static char[] hideWord(String hiddenWord)
{
int wordLength = hiddenWord.length();
//int length = wordLength * 2;
char[] asterisks = new char[wordLength];
for(int i=0; i < wordLength; i++)
{
asterisks[i] = '*';
}
return asterisks;
}
public static void numGuess(String hiddenWord,char[] asterisks)
{
Scanner keyboard = new Scanner(System.in);
hideWord(hiddenWord);
int remAttempts = MAXGUESS;
int i = 0;
while(i < (hiddenWord.length()-1))
{
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
if(asterisks[i] == (hiddenWord.charAt(i)))
{
//attemtps == hiddenWord.charAt(i);
System.out.println("Nice job!");
remAttempts--;
}
i++;
}
}
Look at this code (I changed the formatting a bit):
while (i < hiddenWord.length() - 1) {
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
//...
i++;
}
You're asking for a letter, but you really request a String with at least the size + 1 that equals i: keyboard.next().charAt(i);. Therefore, if you write just a letter, then you'll get an Exception at the second iteration of that loop.
I guess what you meant was: keyboard.next().charAt(0);. This will return the first character of the given String.
If this doesn't solve the problem, then provide the whole Stacktrace and mark the line in your code, where the Exception occurs.