Hangman : Exit the program when the word is found - java

This is an implementation of the Hangman game. Once the user has uncovered the word, the program should exit, but it continues to prompt the user for input although all letters of the word have been correctly guessed.
How can I make the program exit properly once the word has been guessed?
The word to seach is for example no : Here is an illustration:
Enter your lettre:
n
The letter is OK !
n_
Enter your lettre:
o
The letter is OK !
no
Enter your lettre:
I don't understand why the loop continues ? Because I found the word...
Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Random r = new Random();
String[] arr = {"one", "no"};
String word = arr[r.nextInt(arr.length)];
char[] dash = word.toCharArray();
char[] charArr = word.toCharArray();
for(int i=0;i<dash.length;i++){
dash[i] = '-';
System.out.print(dash[i] + " ");
}
System.out.println("");
for(int i=0;i<3;i++){
System.out.print("Enter your letter : ");
char letter = input.next().charAt(0);
for(int j=0;j<charArr.length;j++){
if(letter == charArr[j]){
dash[j] = letter;
System.out.println("Ok ! ");
System.out.println(dash);
i--;
}
}
}
}
}
I share you the code here => https://repl.it/repls/BonyRevolvingOs
Thank you for your help.

Look at the block of code defining your inner loop:
for(int j=0;j<charArr.length;j++){
if(letter == charArr[j]){
dash[j] = letter;
System.out.println("Ok ! ");
System.out.println(dash);
i--; // What is this doing here?
}
}
At the bottom of that block is the line that's blowing up your program. Get rid of it. Your program never exits the loop because you keep resetting the value of the counter for your outer loop i to 0. Every time the loop increments itself normally to 1, you decrement it, so it's always going from 0 to 1 and back to 0.
Because 0 is less than 3, the loop keeps running. If a break statement depended on the value of that counter, it would not have changed the way your program operated at all. If you called break on some other basis, you could have exited, but you would still have had a fundamentally broken program.
This said, you still have a long way to go to get a working implementation of Hangman because as it stands, your user only has as many guesses as the word has letters If you guess wrong, even a single time, you can never complete the word.
You need to find a way to account for incorrect guesses (drawing the parts of the hanged man) and a way to detect and announce victory or failure (right now, your program just exits after two or three guesses whether or not the puzzle is solved). Work on those things, and if you need more help, post separate questions for each problem.

Related

Easy fix for while loop not executing properly second time?

I'm fairly new at java and have a current assignment to take a given word, put the first word at the end, rebuild the word from reverse, and see if it's the same word as the original, such as: grammar, potato, uneven, dresser, banana etc. So far I have this:
Scanner input = new Scanner(System.in);
String original, reverse = "";
String exit = "quit";
int index;
System.out.println("Please enter a word (enter quit to exit the program): ");
original = input.next();
while (!original.equalsIgnoreCase(exit))
{
String endingChar = original.substring(0, 1);
String addingPhrase = original.substring(1);
reverse += endingChar;
for (index = addingPhrase.length() - 1; index >= 0; --index)
{
char ch = addingPhrase.charAt(index);
reverse += ch;
}
if (original.equals(reverse))
{
System.out.println("Success! The word you entered does have the gramatic property.");
}
else
{
System.out.println("The word you entered does not have the gramatic property."
+ " Please try again with another word (enter quit to exit the program): ");
}
original = input.next();
}
input.close();
When I run it and enter the word "banana," it properly recognizes that it is indeed the same backwards when the b is moved to the end, and does the same with the other words listed above, but when I enter a second word on the loop, it never recognizes it properly, and always responds with the print statement from the else block:
Please enter a word (enter quit to exit the program):
banana
Success! The word you entered does have the gramatic property.
banana
The word you entered does not have the gramatic property. Please try again
with another word (enter quit to exit the program):
I'm guessing it's something to do with either the way I made my for loop, or the way I asked for input at the end of the while loop, but like I said I'm fairly new and awful at debugging. Any help would be much appreciated, thanks a lot in advance.
You are changing string reverse in every iteration, but you are not clearing it. So before the end of the loop or at the beginning clear the string for example like so: reverse = "", and then it should be fine.
Just add reverse = ""; in the end of the while loop in order to set the variable reverse to its original state, i.e. empty string

I need to get my Java program to start back at the beginning after an invalid input

I'm currently working on an assignment for school and I am almost done but I just have one large problem I need to fix before I can add the final bit.
I need to create a program that prompts you to enter either 1 or 2, Afterwards it asks you to enter three words/names and saves them into an array.
Then, depending on whether you picked 1 or 2, it prints them in alphabetical order or flips around the lowercase and uppercase letters. I didn't add that part yet because I'm trying to fix a problem related to the very first input.
When you input a number other than 1 or 2, I am instructed to display an error message and ask for input again. I am pretty sure what I need to do is get the entire program to go back to the beginning because copy/pasting the entire program again would be bad, lol
A big problem is probably that I'm using if/else statements with for loops inside when I might need to put the entire thing inside a loop? But I'm not sure what condition I would use to start the loop if I put the entire code in it. I must be missing something here.
With what I have now, it gets stuck saying invalid input even if you put in a 1 or 2.
import java.util.Scanner;
public class IsabellaPiantoniLab5 {
public static void main (String[]args) {
//Ask for input
Scanner input = new Scanner(System.in);
System.out.print("Please choose either a number 1 or number 2.");
int numChoice = input.nextInt();
//if choice is 1 or 2
if (numChoice == 1 || numChoice == 2) {
System.out.println("Please enter three names: ");
String nameInput[] = new String[4];
//input loop
for (int i= 0; i < nameInput.length; i++) {
nameInput[i] = input.nextLine();
}
System.out.println("Values are:");
//display values if 1
if (numChoice == 1) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
//display values if 2
else if (numChoice == 2) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
}
//retry if invalid------i restart from the beginning if this happens
else if (numChoice != 1 || numChoice != 2) {
System.out.println("Invalid value. Please try again.");
//continue;
}
}
}
System.exit(0);
This will terminate the app, thus you can start it again using command line ( START [your app path])
Or
RunTime.getRuntime().exec(“Your app”);
System.exit(0);
Edit I misunderstood the question, I thought you wanted to restart the whole app
After discussing the approach with #csm_dev
It is way either to ask for the user input one more time by emptying the field and showing a message “please enter a valid input” with a clarification message

Two problems, using charAt for undefined input and looping output

So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using .split. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.
My questions are:
How do I use charAt to identify a character at an undefined index (user input with varying lengths)
How do I stop my sentence from reading back after the user decides to continue.
Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.
To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,
backward = "";
To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,
words[count].charAt(words[count].length() - 1);
Note that count is simply words.length - 1 so this can be changed to your liking.
1) So you have this array of strings words. Before adding each word to the backward string, you can use something like: words[count].chartAt(words[count].length() - 1). It will return you the charater at the last position of this word. Now you are able to do you checking to know wether it is a letter or any special char.
2) The problem is not that it is reading the previous line again, the problem is that the backward string still has the previous result. As you are using a + operator to set the values of the string, it will keep adding it together with the previous result. You should clean it before processing the other input to have the result that you want.
here is your code:
import java.util.*;
public class main{
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String[] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
List<String> items = Arrays.asList(words);
Collections.reverse(items);
System.out.println(generateBackWardResult(items)); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
// i use quals ignore case, makes the code more readable
} while (!sentinel.equalsIgnoreCase("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
static String generateBackWardResult(List<String> input){
String result="";
for (String word:input){
result =result +" "+word;
}
return result;
}
} // end class MyTokenTester][1]][1]
there are also some thing to mention:
* never invent the wheel again! (for reverting an array there are lots of approaches in java util packages, use them.)
*write clean code, do each functionality, i a separate method. in your case you are doing the reverting and showing the result in a single method.

Square Free Word in Java

I'm stuck on creating a program to solve a question for a class. I have a main method and a secondary testing method that are working in conjunction to solve this problem, however I can't get the solution to work when there's a change.
The problem is making sure a word is square free, here's an excerpt from the problem:
For this part, implement a method called isSquareFree that takes as input (a reference to ) an array of characters. You may assume that the elements of the array are all lower case letters. (In other words, you do not need to worry about a question like: "is Z the same letter as z?") Your method should test if the given input array of characters is square-free. If it is, the method should print a message stating that, otherwise it should print a message stating that the world is not square-free, where the square subword starts and what that subword is. For example, if the given array contained the word zatabracabrac the method should print: The word, zatabracabrac, is not square free, since it has subword, abrac twice starting at position 4 of the word.
Below is the current code I have, it works in the case that there is a repeating character directly next to each other, but I'm unsure of how to continue to check if there is multiple repeating characters (abab for example) nor am I sure how to print out the repeating subword.
public static void main(String[] args) {
// part (a) of the main
Scanner keyboard = new Scanner(System.in);
System.out.println("***************************");
System.out.println(" Part (a)");
System.out.println("***************************");
do{
System.out.println("Enter a word and then press enter:");
String str=keyboard.next();
char[] word = str.toCharArray();
isSquareFree(word);
System.out.println("Do you want to test another word? Press y for yes, or another key for no");
}while(keyboard.next().charAt(0)=='y');
}
public static void isSquareFree(char[] word){
int sqf = 0;
for(int i=0; i<word.length; i++){
for(int j=0; j<word.length-1;j++){
if (word[j] == word[j+1]){
sqf = 1;
j = word.length;
}
else{
sqf = 2;
}
}
}
if (sqf == 1){
System.out.println();
System.out.println("Not Square Free");
}
else{
System.out.println();
System.out.println("Square Free");
}
}}
I'd also like to add that I'm not allowed to use the arrays class for this question, nor am I allowed to use strings and I cannot change the main method, not can I change the input for my other method.
To see if a sequence of characters repeats, for a given sequence length (say, n), you would replace your if with a loop that compares word[j+x] with word[j+n+x] for each value of x between 0 and n; and only consider them the same if all n match. Thus, you'd need to loop over these n values for x; if you need to consider different values of n, then you'd need yet another loop to go through those.
It isn't clear from your code what you are using i for, but if it is the length of the repeating part (what I've called n), then you'd only need to consider values up to half the length of word (or else there isn't room to repeat it).
To print out a sub word, you could print out each individual letter in order (using print instead of println)

Arrays - square-free word

This is what the program should do:
The word, zatabracabrac, is not square free, since it has subword, abrac twice start-
ing at position 4 of the word.
We are not allowed to use strings, breaks or other complex stuff. I get the square and square not part but am unable to find its place. I think I went wrong some place like I can't figure it out.
public static void main(String[] args) {
// part (a) of the main
Scanner keyboard = new Scanner(System.in);
System.out.println("***************************");
System.out.println(" Part (a)");
System.out.println("***************************");
do{
System.out.println("Enter a word and then press enter:");
String str=keyboard.next();
char[] word = str.toCharArray();
isSquareFree(word);
System.out.println("Do you want to test another word? Press y for yes, or another key for no");
}while(keyboard.next().charAt(0)=='y');
public static void isSquareFree(char[] word){
int z = 0;
for(int i=0; i<word.length; i++){
for(int j=0; j<word.length-1;j++){
if (word[j] == word[j+1]){
z = 1;
j = word.length;
}
else{
z = 2;
}
}
}
if (z == 1){
System.out.println();
System.out.println("Not Square Free");
}
else{
System.out.println();
System.out.println("Square Free");
}
}
}
Downvotes on the question: this is not where you solve your homework... we all went through having homeworks and solved them (well, most of us), and that's partly why we're capable of helping you.
You're checking whether the word contains two consecutive characters which are the same.
That's not what you want, try another solution.
Here's why it does what I said above:
The outer for loop doesn't have an effect on the inner one, since i is not used inside
Index j and j+1 in the same iteration as a character and the next one
Other notes:
j = word.length is the same as break here, try using that, it stops your loop like the end condition was satisfied; read more: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
For easier testing, you might want to use another main function containing only calls like isSquareFree("zatabracabrac".toCharArray());, even multiple ones to see multiple test results at once
This will greatly reduce the change-compile-run-check cycle's length.
You can use a debugger in an IDE (Eclipse or IntelliJ) to see what your program does.
Without debugging you can use println/print/printf calls to see how many iterations you have and what your values during those iterations.
Hints on solution:
As I see you're essentially looking for consecutive k-length subword duplicates
You phrased it right in the comment, the arbitrary length is giving it another level
At each position i try to look for a subword with length k which has a corresponding match starting at i + k (this helps the consecutive constraint)
k can be anything between a letter and half of the string (more than that is overkill since it cannot repeat twice)
I didn't code it, but it would be my first try
In your examples:
borborygmus
^=>
i
borborygmus
^=>
i+k
With k = 3 there is a match
zatabracabrac
^===>
i
zatabracabrac
^===>
i+k
With k = 5 there is a match

Categories

Resources