Hangman: How to compare and replace a dash with a letter found - java

I am learning Java, I know it exists several solutions on stackoverflow but I am stuck. I am trying to create a basic Hangman.
I would like to know how Could I replace a dash with a letter found?
Here is a demonstration:
The word to search is:no
I enter the letter n
You have 5 attempts.
--
Enter your letter: n
I enter the letter o
You have 4 attempts.
--
Enter your letter: o
Idem.
You have 3 attempts.
--
Enter your letter:
Here is my code:
Scanner input = new Scanner(System.in);
char letter = 0; // declares and initialises letter
String[] words = {"yes", "no"}; // declares and initialises an array of words to guess
String word = words[(int) (Math.random() * words.length)]; // chooses random word
boolean[] found = new boolean[word .length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word.length(); i++) {
if ( found[i] ) {
System.out.print(word.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
attempts--;
}
I have to add a loop perhaps?
I share you my code here => https://repl.it/repls/PeriodicLegitimateMatrix

You can use the indexOf(char) method in the String class to check whether the character was in the word.
It should look like this:
while (attemps > 0) {
//...
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
int characterPosition = word.indexOf(letter);//use a loop because the character could appear in more than one position in the word
while (characterPosition != -1) {//if indexOf(char) returns -1 it means the char was not found
found[characterPosition] = true;
characterPosition = word.indexOf(letter, characterPosition);//this time search the character starting from the last position to find the next one
}
attempts--;
}

Related

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

How to find the length of the last word in java?

I want to find the length of the last word to initially find the length of the second word in the phrase. here's my plan, If I find the length of the last phrase then in the for loop if I subtract x, it should give me the length of the second word always. This has to be done using for loop and a scanner, where the user inputs any phrase.
Basically, I need to know how to find the length of the last phrase. Thats what I need to know only.
here's my code:
else if (option == 2){
int counter = 0 ;
for (int x = 0; x < phrase.length() - x; x++){
//in the "int x = 0" i need to put the length of the last word
// in a phrase
char n = phrase.charAt(x);
if (n == x);
counter++;
}
System.out.print("Second word has "+counter+" letters");
}
With only the for-loop, length of last word in the phrase:
else if (option == 2){
int lastSpaceChar = 0;
for (int x = 0; x < phrase.length(); x++){
char n = phrase.charAt(x);
if (n == ' ') { //Indicate space
lastSpaceChar = x;
}
}
//When loop is finished, it will have the index of the last space
//So if you take total length - last space, you'll get the last word
int lengthOfLastWord = phrase.length() - spaceChar;
System.out.print("Last word has " + lengthOfLastWord + " letters");
}
If you want the second word, you need to do the same, except find 1st and 2nd space, because characters between first 2 spaces form the 2nd word.
else if (option == 2){
int firstSpace = -1;
int secondSpace = -1;
for (int x = 0; x < phrase.length(); x++){
char n = phrase.charAt(x);
if (n == ' ' && firstSpace == -1) { //Space found the first time
firstSpace = x;
} else if (n == ' ') {
//FirstSpace has already been found
//So this should be second
secondSpace = x;
break; //No need to look anymore, we have both spaces
}
}
//When loop is finished, you will have first 2 spaces
//Characters between first 2 spaces is 2nd word
int lengthOfSecondWord = firstSpace - secondSpace;
System.out.print("Second word has " + lengthOfSecondWord + " letters");
}
I'm assuming you're just learning, so this will do.
Of course, you should probably do error handling and look out for edge cases in actual practice.
The length of the last word in a sentence can be obtained like this:
public int getLengthOfLastWord(String sentence) {
if (sentence == null || sentence.length() == 0) {
return 0;
}
// Split the sentence into words on space(s).
String[] words = sentence.split("\\s+");
return words[words.length - 1].length();
}
To be accurate, you'll want to do more than just check for spaces between words, because if you are only looking for spaces then it is going to treat punctuation like commas and periods as part of the lengths of words. So your best bet is something like isAlphabetic().
If your plan is to loop through characters in the string (i.e. you don't want to use string functions), one very simple way (that wouldn't require you to change your code much) is to count forward through the array. The first time you find one where:
phrase.charAt(x).isAlphabetic()
is true, you know you've reached the beginning of the first "word" in the phrase.
Then you keep looking forward and when
!phrase.charAt(x).isAlphabetic()
Then you know you've reached the space between the first word and the second word. But there might be punctuation so you keep scanning forward until you're back to isAlphabetic() being true again, at which point you've reached the beginning of the second word. You now start counting characters until you find isAlphabetic() going false again (you've reached a space or punctuation). At which point you know you've reached the end of the second word, and now you can check your character count for how long it was.
This method doesn't count numbers, punctuation, spaces, and special characters as part of a phrase. So you might need to special-case it for things like an apostrophe in a contraction like "don't", but hopefully this gives you a general idea.
There are other approaches, but this is the closest to how you have your code right now. Obviously you can use String functions and get a shorter piece of code, etc, but you asked specifically for a version that conformed to your loop method.
int word_wanted = 2; // Want length of the second word. Or set to -1 if you want the last word.
int counter = 0; // How long is the current word
int on_word = 0; // What word number are we on
boolean in_word = false; // Are we currently in a word
for (int x = 0; x < phrase.length() - x; x++){
if (phrase.charAt(x).isAlphabetic()) {
if (!in_word) {
on_word++;
counter = 0;
in_word = true;
}
counter++;
} else {
if (in_word) {
in_word = false;
if (on_word == word_wanted) break; // Stop if we found the length of the word requested.
}
}
}
// counter now contains the length of the requested word. It can be returned
// as a return value from your method, or used for other purposes.
It is not clear from your question whether you want to find the length of the last word or the length of the second word from the start or the length of the second last word in a phrase. So, I've written solutions to all of these requirements. I've put enough comment in the code so that you can understand it easily.
Length of the last word:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int i;
// Start the loop from the end in the backward direction
for (i = phrase.length() - 1; i >= 0; i--) {
if (phrase.charAt(i) == ' ') {
System.out.println("Length of the last word: " + (phrase.length() - i - 1));
break;
}
}
// If the loop terminated without finding any space, it means there is only one
// word in the phrase
if (i == -1) {
System.out.println("Length of the last word: " + phrase.length());
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the last word: 5
Another sample run:
Enter option: 2
Enter phrase: Good morning
Length of the last word: 7
Another sample run:
Enter option: 2
Enter phrase: Good
Length of the last word: 4
Length of the second word from the beginning:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index = 0, counter = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == ' ') {
if (counter == 0) {
index = i;
}
counter++;
}
// Print the length when space has been found second time, and break the loop
if (counter == 2) {
System.out.println("Length of the second word: " + (i - index - 1));
break;
}
}
// If there are only two words in the phrase, space will be found only once. In
// that case the length of the second word will be phrase.length() - index - 1
if (counter == 1) {
System.out.println("Length of the second word: " + (phrase.length() - index - 1));
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Hello world
Length of the second word: 5
Another sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the second word: 7
Length of the second last word:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index = 0, counter = 0;
// Start the loop from the end in the backward direction
for (int i = phrase.length() - 1; i >= 0; i--) {
if (phrase.charAt(i) == ' ') {
if (counter == 0) {
index = i;
}
counter++;
}
// Print the length when space has been found second time, and break the loop
if (counter == 2) {
System.out.println("Length of second last word: " + (index - i - 1));
break;
}
}
// If there are only two words in the phrase, space will be found only once. In
// that case the length of the second last word (which is the first word out of
// the two words) will be index (as the loop is running in the backward
// direction)
if (counter == 1) {
System.out.println("Length of second last word: " + index);
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of second last word: 7
Another sample run:
Enter option: 2
Enter phrase: Hello world
Length of second last word: 5

How to print a letter involving the indexOf() Method? Note: A letter should be printed instead of the index position [duplicate]

This question already has answers here:
How do I print a letter based on the index of the string?
(2 answers)
Closed 2 years ago.
I want to print a letter based on the index position. Although, there is more added to that but here's the requirement, I know it involves the charAt(); method but how would I use the method to find the string of this following requirement: 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 if the input s "upside down" and "d", then it should output "e" so it should be the character after the input character. Other example, the input is Upside down, and do. The output should be "w"
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter);
char n = phrase.charAt(first + 1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(n);
}
}
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 3) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
System.out.print("Enter a substring to search after: ");
String substring = keyboard.next();
int index;
if (phrase.length() > substring.length()) {
index = phrase.indexOf(substring);
if (index != -1 && index < phrase.length() - substring.length()) {
System.out.println(phrase.charAt(index + substring.length()));
}
if (index == phrase.length() - substring.length()) {
System.out.println("'" + substring + "' is the last substring in '" + phrase + "'");
}
if (index == -1) {
System.out.print("'" + substring + "' is not in '" + phrase + "'");
}
}
}
}
}
A sample run:
Enter option: 3
Enter phrase: upside down
Enter a substring to search after: do
w
Another sample run:
Enter option: 3
Enter phrase: upside down
Enter a substring to search after: down
'down' is the last substring in 'upside down'
Another sample run:
Enter option: 3
Enter phrase: upside down
Enter a substring to search after: x
'x' is not in 'upside down'

Counting matching characters on a string

I have been asked to created a program that asks the user for two inputs, both of which have to be stored as strings. The first input can be one or multiple words, and the second input has to be one sole character. After the user enters both inputs the program should count how many times, if any, the sole charter appears in the first string. Once the iteration through the first string is done the program should then output the number of instances of the second string. Example:
"There is 1 occurrence(s) of 'e' in test."
The program must use the a while loop and string values. This is the solution I have as of right now following the parameters established by the professor
public static void main(String[] args) {
String inputEntry; // User's word(s)
String inputCharacter; // User's sole character
String charCapture; // Used to create subtrings of char
int i = 0; // Counter for while loop
int charCount = 0; // Counter for veryfiying how many times char is in string
int charCountDisplay = 0; // Displays instances of char in string
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
inputCharacter = scan.nextLine();
if (inputCharacter.length() > 1 || inputCharacter.length() < 1) // if user is not in compliance
{
System.out.print("Please enter one character. Try again.");
return;
}
else if (inputCharacter.length() == 1) // if user is in compliance
{
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
System.out.print("There is " + charCountDisplay +
" occurrence(s) of " + inputCharacter + " in the test.");
}
}
This iteration has a bug. Instead of counting all the instances of the inputCharacter variable it only counts up to one, regardless of how many instances appear on the string. I know the problem is in this part of the code:
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
I just can't quiet pin down what I'm doing wrong. It seems to me that the charCountDisplay variable reverts to zero after each iteration. Isn't that supposed to be avoided by declaring the variable at the very beginning?... I'm one confused fellow.
This is wrong
charCapture = inputEntry.substring(charCount);
does not return one char
try using inputEntry.charAt(charCount)
Another hint is to define your variables close to where you use them rather than at the top of your method like:
String inputEntry;
inputEntry = scan.nextLine();
Even better would be to do inline
String inputEntry = scan.nextLine();
It will make your code a lot more concise and readable.
A more concise way to do your code is:
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
String inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
String inputCharacter = scan.nextLine();
// validate
// then
int len = inputEntry.length();
inputEntry = inputEntry.replace(inputCharacter, "");
int newlen = inputEntry.length();
System.out.format("There is %d occurrence(s) of %s in the test.%n",
len - newlen, inputCharacter);
output
Enter some words here: scarywombat writes code
Enter a character here: o
There is 2 occurrence(s) of o in the test.
Here is a complete MVCE:
package com.example.countcharacters;
/**
* EXAMPLE OUTPUT:
* Enter some words here:
* How now brown cow
* Enter a character here:
* abc
* Please enter one character. Try again.
* Enter a character here:
* o
* There are 4 occurrence(s) of o in the text How now brown cow.
*/
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Captures word(s)
String inputEntry;
System.out.println("Enter some words here: ");
inputEntry = scan.nextLine();
// Captures char
char inputCharacter;
while (true) {
System.out.println("Enter a character here: ");
String line = scan.nextLine();
if (line.length() == 1) {
inputCharacter = line.charAt(0);
break;
} else {
// if user is not in compliance
System.out.println("Please enter one character. Try again.");
}
}
// iterates through word(s)
int charCountDisplay = 0;
int i = 0;
while(i < inputEntry.length()) {
char c = inputEntry.charAt(i++);
if (c == inputCharacter) {
++charCountDisplay;
}
}
// Print results
System.out.print("There are " + charCountDisplay +
" occurrence(s) of " + inputCharacter +
" in the text " + inputEntry + ".");
}
}
NOTES:
You can use "char" and "String.charAt()" to simplify your code.
In general, it's preferable to declare variables close to where you use them (rather than at the top).
You can put your test for "one character only" in its own loop.
'Hope that helps!
inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() will give you the number of occurrences of a character in the string.
String inputEntry = "text";
char inputCharacter = 'x';
System.out.print("There is " + inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() + " occurrence(s) of " + inputCharacter + " in the text " + inputEntry + ".");

java characters in a string

so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));

Categories

Resources