really beginner javascript user here, creating a hangman game. i am having the world of difficulty in trying to show a users correct guess.
from my understanding i have only masked the secret word with dashes so therefor am trying to make it become unmasked when a correct letter is guessed.
i imagine i need to use charAt somewhere, somehow but to be honest i just cant figure it out.
My code is still very basic and i havent done much else as there isnt much point writing out the rest of the game if you cant see the guess but here is the code i have so far... please remember this is still a very unfinished project.
package hangmangame;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/**
*
* #author Matt
*/
public class HangmanGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
char letter = 0; //declares and initailise letter
String marks = ""; //declares and initailise string for dashes
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
for (int i=1;i<=word.length(); i++) // for method for displaying the correct word as dashes
{
marks += "-"; //dashes to represent the correct word.
}
System.out.println("lets play hangman, your word is " + marks + "\n" + "enter a letter to guess the word");
Scanner input = new Scanner(System.in);
letter = input.next(".").charAt(0); //assign inputted letter to letter variable
if ((word).contains(""+letter)) //if statement to excute if guessed letter is in word
// i imagine this is where i put some sort of code to show that guessed letter?
System.out.println("You guessed a letter!" + marks); //display for correct letter
Here is some code to get you started. It's important to grab the entire line from the user instead of using next()... Unless you are an experienced coder and understand the way in which the next() iterates over the input I'd highly suggest using nextLine() as it's much easier to use.
char letter = 0; //declares and initailise letter
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
String [] marks = new String[word.length()];
for (int i=0;i<word.length(); i++) // for method for displaying the correct word as dashes
{
marks[i] = "-"; //dashes to represent the correct word.
}
HashSet<Character> lettersGuessed = new HashSet<>(); //keep track of letters guessed
Scanner input = new Scanner(System.in);
String userInput = "";
String currentWord = "";
while(true)
{
System.out.print("Word is - ");
currentWord = "";
for(int i = 0; i < marks.length; i++)
{
System.out.print(marks[i]);
}
System.out.print("\nGuess a letter - ");
userInput = input.nextLine(); //always grab lines
if(userInput.length() != 1)
{
System.out.println("Invalid guess - " + userInput);
}
else if(lettersGuessed.contains(userInput.charAt(0)))
{
System.out.println("You already guess that character - " + userInput);
}
else if(word.contains(userInput))
{
lettersGuessed.add(userInput.charAt(0));
currentWord = "";
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == userInput.charAt(0))
{
marks[i] = "" + userInput.charAt(0);
}
currentWord += marks[i];
}
}
if(currentWord.equals(word))
break;
}
System.out.println("You guessed it! The word was " + word + "!");
Output
Word is - ----
Guess a letter - l
Word is - --l-
Guess a letter - h
Word is - h-l-
Guess a letter - l
You already guess that character - l
Word is - h-l-
Guess a letter - u
Word is - hul-
Guess a letter - tg
Invalid guess - tg
Word is - hul-
Guess a letter - k
You guessed it! The word was hulk!
the String class contains an indexOf(String c) method which returns the index of the first occurrence of a substring. For example, if word was delicious then word.indexOf("i") would return 3, the first index of the substring "i".
But what about all other occurences of the substring "i"? Well, the indexOf method is handily overwritten to help with that. There is another version of it, indexOf(String ch, int fromIndex) that takes in a starting index. Continuing our earlier example, if you asked for word.indexOf("i", 4) this time you would get back 5, the first index of the substring "i" in the string "delicious" if we are discounting every index before the fourth one.
Think of it this way, indexOf is kind of the opposite of charAt. charAt takes in an index and gives you a character, indexOf takes in a character or string and gives you its first index.
I think this would all be a lot easier if you stored the word and the marks as character arrays like this:
char letter = 0; //declares and initailise letter
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
char[] chosenWord = new char[word.length()];
char[] marks = new char[word.length];
for (int i=0;i< word.length(); i++) // for method for displaying the correct word as dashes
{
chosenWord[i] = word.charAt(i);
marks[i] = '-';
}
System.out.println("lets play hangman, your word is " + new String(marks) + "\n" + "enter a letter to guess the word");
Scanner input = new Scanner(System.in);
letter = input.next(".").charAt(0); //assign inputted letter to letter variable
if ((word).contains(""+letter)){ //if statement to excute if guessed letter is in word
for(int i =0; i < chosenWord.length; i++){
if(chosenWord[i] == letter){
marks[i] = chosenWord[i]
}
}
// i imagine this is where i put some sort of code to show that guessed letter?
System.out.println("You guessed a letter!" + new String(marks));
}
I didn't syntax check this, but you should get the idea of what I'm working at.
This is what i made.
I think its much better to use arrays here.
public static void main(String[] args) {
String[] words = {"gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi", "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word[] = (words[(int) (Math.random() * words.length)]).split(""); //chooses random word from the word array and creates a array of letters
String[] marks = new String[word.length];
Arrays.fill(marks,"-"); // creates and fills an array with dashes
Scanner in = new Scanner(System.in);
String letter = "";
int counter = 0;
while(Arrays.toString(marks).contains("-")) {
counter++;
System.out.println("This is your word!: " + String.join("", marks));
System.out.print("Guess a letter ");
letter = String.valueOf(in.next(".").charAt(0));
for (int i = 0; i < word.length; i++) {
if(word[i].equals(letter)){
marks[i] = word[i];
}
}
}
System.out.println("Congratulations your word is " + String.join("",marks) + "You did it in " + counter + "trials");
}
}
Related
This project is used to identify whether or not a user's input is a palindrome, and if it's not, identifies how many characters don't match and their positions in the string (i.e characters 2 and 4 don't match). I've been able to figure out how to identify whether or not a string is a palindrome, but I'm struggling with how to specifically identify the characters that don't match in a non-palindrome. Here's my code so far:
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
String stringInput = "";
String inputReverse = "";
boolean isPalindrome = true;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
stringInput = keyboard.nextLine();
int stringLength = stringInput.length();
for(int i = stringLength - 1; i >=0; i--)
{
inputReverse = inputReverse + stringInput.charAt(i);
}
if(stringInput.equals(inputReverse))
{
System.out.println(stringInput + " is a valid palindrome.");
}
else
{
System.out.println(stringInput + " is not a valid palindrome.");
}
}
}
the output I want for when a string is not a palindrome is:
"The characters at index 0 and 3 do not match.
goop is not a valid palindrome.
number of invalid character matches: 1 "
I tried to use stringInput.charAt(0) but the user input is unpredictable, so I wouldn't be able to use char 0,1,2,3 etc forever. Any help?
Iterate from both ends of the string, moving toward the center and checking the corresponding characters each time.
int nomatch = 0;
for (int i = 0, j = stringLength - 1; i < j; i++, j--) {
if (stringInput.charAt(i) != stringInput.charAt(j)) {
++nomatch;
System.out.format("The characters at index %d and %d do not match.%n", i, j);
}
}
if (nomatch == 0) System.out.println(stringInput + " is a palindrome.");
else System.out.println(stringInput + " is not a palindrome. Number of invalid character matches: " + nomatch);
As this is home work, I'll only give general hints:
an easy way to reverse a string is inputReverse = new StringBuilder(stringInput).reverse().toString();
you only need to compare each character of the first half of the input with its reverse
use a for loop of int from 0 to half the length and pass it to charAt() for both strings and compare using ==
store the indexes of differences in a List<Integer>
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
This is my first submission, I have completed one quarter of Java programming.
I have an assignment to create a Palindrome Checker. Fairly straight forward, I had that portion of the code figured out in the first hour. However, in typical fashion (for me) I want my code to do a bit more. This is where I run into issues.
I want this code to do the following:
Take user input
Correctly identify if the input is a palindrome regardless of case or punctuation
Run in a loop so that multiple tests can be performed
So far it works, I just don't know if I went about it the right way. Would anyone be willing to take a look and let me know how inefficient this is, or if it has any obvious rookie mistakes? Thanks so much.
Code:
/**
* Created by Travis on 1/10/2015.
*/
import java.io.IOException;
import java.util.*;
import javax.swing.*;
import java.text.*;
import java.lang.StringBuilder;
public class Palindrome
{
public static void main(String[] args) throws IOException //main class
{
String str = "", answer = "", test1 = "yes", test2 = "no"; //strings
int len = 10; //initial value for len so it doesn't trip the success if
Scanner KB = new Scanner(System.in); //user input
System.out.println("Greetings, Welcome to the Palindrome Checker.\n" + //initial greeting
"Would you like to check a Palindrome? (Yes or no)");
answer = KB.nextLine(); //input is for the sentinel program.
if (!(answer.equalsIgnoreCase(test1) || answer.equalsIgnoreCase(test2))) //error message in case user inputs incorrect string.
{
System.out.println("Error! You can only choose 'yes' or 'no'. Please try again:");
answer = KB.nextLine(); //allows for new answer
}
System.out.println(answer + " y"); //debugging so i can see answer
while (answer.equalsIgnoreCase(test1)) //compares to test1 which is: yes. as long as answer equals yes, the program should loop
{
System.out.println("Please provide a word or phrase:");
str = KB.nextLine(); //prompt for palindrome
String str2 = str.toLowerCase().replaceAll("\\s+", "").replaceAll("\\W+", ""); //converts input to a string that is a single group of chars with no space or punctuation
System.out.println(str2); //debug
StringBuilder str1 = new StringBuilder(str2); //takes the string and makes a stringbuilder so i can delete chars to test
len = str1.length(); //sets for length. This lets me account for any length of phrase
System.out.println(len); //debug
System.out.println(str1); //debug
for (int i = 0; len >= 2; i++) //for loop to progressively test front and back letters and proceed if they are the same
{
char ch1 = str1.charAt(0); //takes the letter at [0] and converts to char
char ch2 = str1.charAt(len - 1); //takes the last letter and converts to char
System.out.println("The first letter in your phrase is: " + ch1); // lists the letter at [0]
System.out.println("The last letter in your phrase is: " + ch2); //lists the letter at the end
if (!(ch1 == ch2)) //if the front and back letter do not match, fails and prompts for new phrase
{
System.out.println("Sorry, this phrase is not a palindrome. \n" +
"Would you like to try again?");
answer = KB.nextLine();
break;
}
else if (ch1 == ch2) //if front and back do match, removes front and back letters and updates stringbuilder
{
System.out.println("Removing letters on each end of the phrase and performing " +
"new check:\n");
str1.deleteCharAt(len - 1); //deletes the last letter from str1
str1.deleteCharAt(0); //deletes first letter from str1
len = str1.length(); //updates len with the new length of str1
i++;
}
}
if (len <= 1) //if the for loop successfully reduces stringbuilder to 1 or less characters, prompts for success
{
System.out.println("Congratulations, your phrase: '" + str + "' is a palindrome! \n\n" +
"Would you like to try again?");
answer = KB.nextLine();
len = 10; //resets len
}
}
if (answer.equalsIgnoreCase(test2)) //ends sentinel loop.
{
System.out.println(answer + " N");
System.exit(0);
}
}
}
So currently im trying to do a java project and have seen a few answers on this on other websites but im having trouble understandign them. i need to do this:
"Write a program that prompts the user to input a string of words, then counts and displays the number of times each letter in the alphabet appears in the string. It is not necessary to distinguish between uppercase and lowercase letters. Your output should be formatted as follows:
Letter A count = xx
Letter B count = xx
....
Letter Z count = xx"
and this is what I have so far:
import java.util.Scanner;
public class Unit9 {
public static void main(String [] args )
{
int array[] = new int[26];
for (int i = 0; i < array.length; i++)
{
array[i] = 0;
}
Scanner Keyboard = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string.");
userInput = Keyboard.next().toLowerCase();
for (int i = 0; i < userInput.length(); i++)
{
char ch = userInput.charAt(i);
if (ch >= 'a' && ch <= 'z') {
array[ch - 'a'] ++;
}
}
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + array[ch-'a']);
}
}
}
but when i enter "hello" (without the quotes) i end up getting this:
Please enter a string.
hello
979899100102102103105105106107110109110112112113114115116117118119120121122
what is happening? what am i doing wrong?
EDIT: actually, i just realized something else... it stops detecting when there is a space in the user input meaning that it only detects the first word. how would I add detection for a space as well?
The reason why it only detected the first word is because you entered:
userInput = Keyboard.next().toLowerCase();
instead of
userInput = Keyboard.nextLine().toLowerCase();
nextLine() reads the whole line entered while next() only reads the first word.
You are using the + operator between a char and an int on this line:
System.out.print(ch + array[ch-'a']);
This gives you a number as a result, which is then inputted into System.out.print taking int as input, therefor printing the number itself. You also have no spacing (or use println), so it appears to be one long line of numbers.
Try this for your last loop:
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + ": "+ array[ch-'a']+" ");
}
It will now no longer be seen as addition, but rather concatination and show as a string of "letter: amount", one after another for the entire alphabet.
Question 1:
I am trying to count the frequency of a keyword, my code works except that it also counts
those words that also contain the keyword (for example, if I search "count", words like "account" will also be counted in.) Does someone know how to solve this?
Question 2:
I also wanna count the the number of unique words in a text (which means I count repeated word only once). I don't know how to achieve this either. My code only gives me the number of total words.
Here is my code:
import java.util.Scanner;
public class Text_minining {
/**
* #param args
*/
public static void main(String[] args) {
//Prompt the user for the search word
System.out.print("enter a search word: ");
//Get the user's search word input
Scanner keywordScanner = new Scanner(System.in);
String keyword = keywordScanner.nextLine();
keyword = keyword.toLowerCase();
//Prompt the user for the text
System.out.println("Enter a string of words (words separated by single spaces or tabs): ");
//Get the user's string input
Scanner userInputScanner = new Scanner(System.in);
String userInput = userInputScanner.nextLine();
userInput = userInput.toLowerCase();
int keywordCount = 0, wordCount = 0;
int lastIndex = 0;
while(lastIndex != -1){
lastIndex = userInput.indexOf(keyword,lastIndex);
if(lastIndex != -1){
keywordCount ++;
lastIndex = keyword.length() + lastIndex;
}
}
boolean wasSpace=true;
for (int i = 0; i < userInput.length(); i++)
{
if (userInput.charAt(i) == ' ') {
wasSpace=true;
}
else{
if(wasSpace == true) wordCount++;
wasSpace = false;
}
}
//Print the results to the screen
System.out.println("-------");
System.out.println("Good, \"" + keyword + "\"appears in the text and the word count is " + keywordCount);
System.out.println("The total number of unique words in the text is " + wordCount);
System.exit(0);
}
}
First: userInput.split(keyword).length - 1 will do the trick. Our use regex.
Second:
Set<String> uniqueWords = new HashSet<String>();
for (String word : userInput.split(" ")) {
uniqueWords.add(word);
}
System.out.println("Unique words count " + uniqueWords.size());
Just use string method split.
String words[] = userInput.split(keyword);
and then check and count the keyword...
for ( String w : words) {
// do check
}
Agree. Use split to create the array and then you can use
(new HashSet(Arrays.asList(yourArray))).size();
to find the count
I would suggest you this approach:
Split userInput string by white spaces: userInput.split("\\s+"). You will get an array. See String.split()
For question 1: iterate over the array comparing each string with your keyword. See String.equals() and String.equalsIgnoreCase().
For question 2: add the array to a Set. As this can't contain any duplicate item, its size will give you the answer.