Having dashes change into guessed letters - java

my program currently takes a random word and turns into dashes based on how many letters are in the word. I then determine if a letter guessed is in the word, but I was unable to figure out how to have the correctly guessed letter replace the dashes accordingly. I looked through possible solutions on the site, but was unable to have one work for my current code.
Code:
public String hiddenWord(){
word = randomWord.getRandomWord();
String dashes = word.replaceAll("[^ ]", " _ ");
return dashes;
}
public String guessNotification(){
if(word.indexOf(hv.keyChar)!=-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
letterGuessed = "There is a " + hv.keyChar + " in the word";
}
else if(word.indexOf(hv.keyChar)==-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
letterGuessed = "No " + hv.keyChar + " in the word";
guesses++;
System.out.println(guesses);
}
else{
letterGuessed = "Not a valid letter";
}
return letterGuessed;
}
public void newGame() {
hv.createNotification(this, size);
guesses = 0;
System.out.println(word);
}
}

Here is how the logic of how to replace the appropriate dash with the correct user guess might look
public static String guessNotification(String word, char userGuess, StringBuilder dashes) {
int guessedIndex = word.indexOf(userGuess);
if (guessedIndex != -1 && (userGuess >= 'a' && userGuess <= 'z')) {
letterGuessed = "There is a " + userGuess + " in the word";
dashes.setCharAt(guessedIndex*3+1, userGuess);
}
else if (guessedIndex == -1 && (userGuess >= 'a' && userGuess <= 'z')) {
letterGuessed = "No " + userGuess + " in the word";
guesses++;
}
else {
letterGuessed = "Not a valid letter";
}
return letterGuessed;
}

Comments are all correct. But you may want to see example code: Add an array of correct guesses:
char[] correct = new char[26]; // or more, depends on whether u use non ascii chars
Initialize the array with e.g. ' '. Then replace the dashes:
StringBuilder guessedPart = new StringBuilder;
for (int lc = 0; lc < word.lenght(); lc++) {
for (char c : correct)
if (word.indexOf(lc) = c) guessedPart.append(c);
if (guessedPart.length() < lc) guessedPart.append('_');
String guessedWord = guessedPart.toString();
That should do.

Related

I want to print the number of vowels, consonants, spaces, digits and special characters in the string entered by user [duplicate]

This question already has answers here:
StringIndexOutOfBoundsException in a counting loop in Java
(3 answers)
Closed 2 years ago.
I need to print no. of vowels, consonants, spaces, digits and special characters in the string entered by user.
I am getting below error after running the program.
Input: Enter the word to count Vowels and Alphabets in it
java language version 15#
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.lang.String.charAt(String.java:658)
at CountAlphabetsInWord.main(CountAlphabetsInWord.java:11)
public class CountAlphabetsInWord {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the word to count Vowels and Alphabets in it");
String word = scanner.nextLine();
scanner.close();
int vowels = 0, consonants = 0, spaces = 0, digits = 0, specialCharacters = 0;
word = word.toLowerCase();
for(int i = 0; i <= word.length(); i++){
char ch = word.charAt(i);
//check if any char is a, e, i, o ,u
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'){
vowels++;
}
else if(ch >= '0' && ch <= '9'){
consonants++;
}
else if(ch == ' '){
spaces++;
}
else if(ch >= 'a' && ch <= 'z'){
digits++;
}
else
specialCharacters++;
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Digits: " + digits);
System.out.println("WhiteSpaces: " + spaces);
System.out.println("Special Characters: " + specialCharacters);
}
} ```
Consider using an enhanced for loop so you don't have to worry about index out of bound errors, and for similar reasons utilize the inbuilt Character methods:
import java.util.Scanner;
import java.util.Set;
public class AnalyzeStringInput {
private static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o', 'u');
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a string:");
String string = scanner.nextLine();
int vowels = 0, consonants = 0, spaces = 0, digits = 0, specialCharacters = 0;
for (Character ch : string.toLowerCase().toCharArray()) {
if (Character.isLetter(ch)) {
if (VOWELS.contains(ch)) {
vowels++;
} else {
consonants++;
}
} else if (Character.isSpaceChar(ch)) {
spaces++;
} else if (Character.isDigit(ch)) {
digits++;
} else {
specialCharacters++;
}
}
System.out.println();
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Spaces: " + spaces);
System.out.println("Digits: " + digits);
System.out.println("Special Characters (anything else): " + specialCharacters);
}
}
Example Usage:
Please enter a string:
AbcDeF gHi JkLmnO 1234% ~!56&*()
Vowels: 4
Consonants: 11
Spaces: 5
Digits: 6
Special Characters (anything else): 7
The index word.length() is beyond the range of characters in word. Remember, it’s zero-indexed, so the range of characters is 0 to word.length - 1.
You just need to tweak your for-loop:
for(int i = 0; i < word.length(); i++){
use "i<word.length()" in for loop

Trying to end loop when user input = q

Essentially I am trying to create a Pig Latin converter. However, for this assignment a requirement is to allow the user to enter 'Q' to quit entering in words. I can get the code to compile, but whenever the user enters Q it crashes and throws:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at mission4aa.Mission4AA.main(Mission4AA.java:38)
I am just completley unsure where to even go about fixing this. I've been trying.
import java.util.Scanner;
public class Mission4AA {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
System.out.println("Enter another word(Q to exit): ");
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
}
Because when you are doing this check
if(userInput.charAt(1) != firstVowel) {
If the user has input a 'q', userInput will only have a 0 term ( Length 1 ). You are effectively trying to get the second character of the users input. To solve your problem, i would do the check for 'q' at the start of the do section ( or simply scrap the do-while concept and use a while(true) loop ). Note that in future you should handle input that is of length 1. But for your issue, something like this would work
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
//here
if(userInput.equals("q") || userInput.equals("Q")){
System.out.println("Thank you");
return;
}
//else continue
If the user enters just Q or q - there's no char at index 1, which is why your code throws the java.lang.StringIndexOutOfBoundsException exception.
There are many ways to fix this. In my case, I just converted your do-while to a while(true) and I use break if the input is just Q or q.
// get first input
userInput = scanIn.next();
while(true){
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
// check next word here - if Q or q, break out and finish
userInput = scanIn.next();
if(userInput.equalsIgnoreCase("q")) {
break;
}
System.out.println("Enter another word(Q to exit): ");
}
Note - you'd need to rearrange your print statements accordingly.
The problem appears to be that you read the user input in the beginning of the loop, thus the condition in your do-while loop checks the previous user input - not the new one.
In addition the else-branch of your if-statement assumes that the input is at least 2 characters long if(userInput.charAt(1) != firstVowel) {...}.
This is what causes the exception as the input "q" reaches the else-branch, but is only of length 1.
You need to make two changes to your code:
You need to read the userinput before checking the loop-condition.
In the else-branch you must check that the input is at least 2 characters long before checking if the second character is a vowel.
Modified code below:
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
do {
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(end > 1 && userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
} else { /* Handle handle input of length 1 */}
}
System.out.println("Enter another word(Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}

PigLatin program help...Capitalize?

I have the program working except for the capitalization part:
Here's how to translate the English word englishWord into the Pig Latin word pigLatinWord:
a. If there are no vowels in englishWord, then pigLatinWord is just englishWord + "ay". (There are ten vowels: 'a', 'e', 'i', 'o', and 'u', and their uppercase counterparts.)
b. Else, if englishWord begins with a vowel, then pigLatinWord is just englishWord + "yay".
c. Otherwise (if englishWord has a vowel in it and yet doesn't start with a vowel), then pigLatinWord is end + start + "ay", where end and start are defined as follows:
1. Let start be all of englishWord up to (but not including) its first vowel.
2. Let end be all of englishWord from its first vowel on.
3. But, if englishWord is capitalized, then capitalize end and "uncapitalize" start.
How do you do the capitalization part?
So far, I get Hasta= astaHay. It should be Hasta = Astahay
Here is the basic program so far:
public static boolean isVowel(char c) {
if (c == 'a' && c == 'A') {
return true;
} else if (c == 'e' && c == 'E') {
return true;
} else if (c == 'i' || c == 'I') {
return true;
} else if (c == 'o' || c == 'O') {
return true;
} else if (c == 'u' || c == 'U') {
return true;
} else {
return false;
}
}
public static String convertPigLatinWord(String englishWord) {
int length = englishWord.length();
if (englishWord.charAt(length - 1) == '.' && englishWord.charAt(length - 1) == '!' && englishWord.charAt(length - 1) == '?') {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1, length - 1);
return (rest + ch + "ay" + englishWord.charAt(length - 1) + "\"" + " ");
} else if (isVowel(englishWord.charAt(0))) {
return (englishWord + "yay" + " ");
} else {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1);
return (rest + ch + "ay" + " ");
}
}
public String translate() {
String pigLatinPhrase = "";
while (englishPhrase.length() > 1) {
String word = getWord();
pigLatinPhrase += convertPigLatinWord(word) + " ";
}
return pigLatinPhrase;
}
public static void main(String[] args) {
String answer = "";
do {
Scanner keyboard = new Scanner(System.in);
String input;
System.out.print("Please enter an English phrase: ");
input = keyboard.nextLine();
PigLatin3 first = new PigLatin3(input);
System.out.println(first.translate());
System.out.println("Would you like to translate another phrase? (y or n)");
answer = keyboard.nextLine();
} while (!(answer.equals("N")) && !(answer.equals("n")));
System.exit(0);
}
}
You can capitalize a letter by breaking the string to substrings and then capitalizing them:
String word = word.substring(0, 1).toUpperCase() + word.substring(1);
So just use the toUpperCase() and toLowerCase() methods of String ...
There is also a neat trick that you can use with single characters based on the ASCII table. Just xor them with 32 to get the other case.
What you are looking for is something like this:
public static String onlyFirstLetterUpperCase(String a){
int i;
for (i = 0; i < a.length(); i++){
if("AEIOUaeiou".indexOf(a.charAt(i)) != -1 )
break;
// indexOf looks for a char in a given string and returns its
// position or -1 if not found. So if this indexOf returns -1 I can be sure,
// that the character is not a vowel
}
return a.substring(0, i + 1).toUpperCase() + a.substring(i + 1).toLowerCase();
}
Just call this method after performing your operations

easier way to find vowels and print them? JAVA

Hey this is my first time posting! I got my program to print out the vowels from an input from user but I feel like I have repeated myself a lot in the for loop. Is there a quicker way to do this? Also is this code readable and in the correct format?
import java.util.Scanner;
public class Task09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String vowels ="";
//input from user
String answer= input.next()
//loop to find vowels
for(int i = 0 ;i<answer.length();i++)
{
char answerPosition = answer.charAt(i);
//checks if there are vowels in code
if (answerPosition =='a'
||answerPosition =='e'
||answerPosition =='i'
||answerPosition =='o'
||answerPosition =='u'
||answerPosition =='A'
||answerPosition =='I'
||answerPosition =='O'
||answerPosition =='U')
{
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}
Try this:
String newString = answer.replaceAll("[^AaeEiIoOuU]", "");
System.out.println(newString);
You wont need for loop as well and your code would be compact and sweet.
You could do:
if ( "aeiouAEIOU".indexOf(answerPosition) >= 0 ) {
vowels += answerPosition + " ";
}
inside the loop.
Additionally, as a matter of style, you might write the iteration slightly differently:
for (char c: answer.toCharArray()) {
if ( "aeiouAEIOU".indexOf(c) >= 0 ) {
vowels += c + " ";
}
}
You can do this way too.
import java.util.Scanner;
public class Hi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String vowels = "";
// input from user
String answer = input.next();
// loop to find vowels
for (int i = 0; i < answer.length(); i++) {
char answerPosition = answer.charAt(i);
char tempAnsPos = Character.toUpperCase(answer.charAt(i));
// checks if there are vowels in code
if (tempAnsPos == 'A' || tempAnsPos == 'E' || tempAnsPos == 'I' || tempAnsPos == 'O' || tempAnsPos == 'U') {
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}

Not sure how to approach english into latin pig java code

Here's my attempt to write this code but I'm getting lost with a main part.I'm not sure how the loop will know when a new word starts.For now I know only loops and if-else statements.I would really appreciate if you could just push me in a right direction because this problem is way too hard for me.
Rules of pig latin:
1)If a word begins with a vowel,add a dash and "way" to the end.
2)Otherwise,add a dash,move the first letter to the end,and add "ay"
/*Enter a line of text: This is a test.
Input: this is a test.
Output: his-tay is-way a-way est-tay.
*/
import java.util.Scanner;
public class PigLatin
{
public static void main(String[]args)
{
int count;
String input;
char empty = ' ',first;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
input = keyboard.nextLine();
System.out.println();
for(count = 0; count < input.length(); count++)
if(input.charAt(0) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(count + 1) + "-" + input.charAt(0) + "ay");
else if(input.charAt(count) == empty)
first = input.charAt(count + 1)
if(input.charAt(first) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(first + 1) + "-" + input.charAt(first) + "ay");
else if()
System.out.print("-way"); //I'm lost here.
}
}
Try the following:
import java.util.Scanner;
public class PigLatin {
static final char vowelRegex = "^[aeiouy]"; //Is y a vowel?
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String input = keyboard.nextLine();
String[] words = input.split(' ');
for(int i=0; i<words.length; i++) {
if(words[i].matches(vowelRegex)) {
System.out.print(words[i] + "-way ");
} else {
System.out.println(words[i].substring(1) + words[i].charAt(0) + "-ay ";
}
}
}
}

Categories