This question already has answers here:
String contains - ignore case [duplicate]
(5 answers)
Closed 1 year ago.
My input here need to be not case-sensitive. I'll show you my code please help, I have zero idea how to do it. Do I need to re write my code for it to be not case-sensitive?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s, x;
System.out.print("Enter a sentence: ");
s = sc.nextLine();
char[] c = s.toCharArray();
int vowel=0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u')
vowel++;
}
System.out.println("There are "+ vowel + " vowels in the sentence");
System.out.print("\nEnter a substring that you want to search: ");
x = sc.nextLine();
boolean check = s.contains(x);
if (check){
System.out.println("There is a substring '" + (x.toUpperCase()) + "' in the sentence");
}
else
System.out.println("There is no substring '" + x + "' in the sentence");
System.out.println("\nThe entered sentence in uppercase characters.");
System.out.println(s.toUpperCase());
}
Should make the string entirely to lower case or upper case. Use this while taking input:
s = sc.nextLine().toLowerCase();
and also:
x = sc.nextLine().toLowerCase();
The complete main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s, x;
System.out.print("Enter a sentence: ");
s = sc.nextLine().toLowerCase();
int vowel=0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u')
vowel++;
}
System.out.println("There are "+ vowel + " vowels in the sentence");
System.out.print("\nEnter a substring that you want to search: ");
x = sc.nextLine().toLowerCase();
boolean check = s.contains(x);
if (check){
System.out.println("There is a substring '" + (x.toUpperCase()) + "' in the sentence");
}
else
System.out.println("There is no substring '" + x + "' in the sentence");
System.out.println("\nThe entered sentence in uppercase characters.");
System.out.println(s.toUpperCase());
}
I'm currently coding a program that takes in a string and a single character (if you decide to put a single one in that is) and (is supposed) to check how many times that character is in the string and at the end print out the amount of times it is in there. For some reason it isn't working and I would like some help; thank you!
import java.util.Scanner;
public class HowManyChars {
public HowManyChars() {
Scanner sc = new Scanner (System.in);
String askPhrase;
String askChar;
int charCounter = 0;
System.out.println("Enter a phrase");
askPhrase = sc.nextLine();
System.out.println("Enter a letter");
askChar = sc.nextLine();
for (int i = 0; i < askPhrase.length(); i++) {
if (askPhrase.substring(i, i + 1) == askChar) {
charCounter = charCounter + 1;
}
}
System.out.println("There are " + charCounter + " " + askChar + " in " + askPhrase);
}
}
I give credit for this answer to #Mushif, who correctly figured out the problem. Your current comparison logic is comparing a string against a character:
for (int i=0; i < askPhrase.length(); i++) {
// String char
if (askPhrase.substring(i, i + 1) == askChar) {
charCounter = charCounter + 1;
}
}
Try iterating the character set of the input word and then compare apples to apples:
for (int i=0; i < askPhrase.length(); i++) {
if (askPhrase.charAt(i) == askChar) {
charCounter = charCounter + 1;
}
}
You could also use an enhanced loop directly on the input's character set:
for (char chr : askPhrase.toCharArray()) {
if (chr == askChar) {
charCounter = charCounter + 1;
}
}
import java.util.Scanner;
public class HowManyChars {
public HowManyChars() {
Scanner sc = new Scanner (System.in);
String askPhrase;
char askChar;
char[] askChars;
int charCounter = 0;
System.out.println("Enter a phrase");
askPhrase = sc.nextLine();
askChars = askPhrase.toCharArray();
System.out.println("Enter a letter");
askChar = sc.next().charAt(0);
sc.close();
for (int i = 0; i < askChars.length; i++) {
if (Character.toLowerCase(askChar) == Character.toLowerCase(askChars[i])) {
charCounter ++;
}
}
System.out.println("There are " + charCounter + " " + askChar + " in " + askPhrase);
}
}
I am new to this and I am having hard time with this code. I made a hangman game but I am having issues with the words that have a capital letter. If I don't input a capital letter the letter will not appear.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Hangman {
static ArrayList<String> words = new ArrayList<>();
static boolean isCorrect;
private static Scanner input;
private static Scanner input2;
public static void main(String[] args) {
File filename = new File("hangman.txt");
if (!filename.exists()) {
System.out.println(filename.getAbsolutePath());
System.out.println(filename + " does not exist.");
System.exit(1);
}
try {
input2 = new Scanner(filename);
while (input2.hasNext()) {
words.add(input2.next());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
input2.close();
input = new Scanner(System.in);
String playStarts = "y";
int wins = 0;
int loses = 0;
final int MAX_GUESSES = 11;
List<String> usedWords = new ArrayList<>();
while (playStarts.equals("y")) {
String word = getWord();
usedWords.add(word);
String secretWord = getSecretWord(word);
int missCount = 0;
while (!word.equals(secretWord)) {
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().charAt(0);
if (!isAlreadyInWord(secretWord, ch)) {
secretWord = getGuess(word, secretWord, ch);
if (!isCorrect) {
System.out.print(ch + " is not in the word.");
missCount++;
System.out.println(" You missed "+ missCount + " times");
}
} else {
System.out.println(ch + " is already in word.");
}
if (missCount == MAX_GUESSES) {
System.out.println("You reached max number of guesses.");break;
}
}
if (missCount == MAX_GUESSES) {
loses++;
} else {
wins++;
}
System.out.println("The word is " + word + ". You missed " + missCount + " times");
System.out.println("Do you want to guess another word? Enter y or n >");
playStarts = input.next();
}
System.out.println("Number of wins is " + wins + ".");
System.out.println("Number of loses is " + loses + ".");
System.out.println("Used words:");
for (String word : usedWords) {
System.out.println(word);
}
input.close();
}
public static String getWord() {
return words.get((int) (Math.random() * words.size()));
}
public static String getSecretWord(String word) {
String hidden = "";
for (int i = 0; i < word.length(); i++) {
hidden += "*";
}
return hidden;
}
static public String getGuess(String word, String secretWord, char ch) {
isCorrect = false;
StringBuilder s = new StringBuilder(secretWord);
for (int i = 0; i < word.length(); i++) {
//I think the issue is in this section of the code:
if (ch == word.charAt(i) && s.charAt(i) == '*') {
isCorrect = true;
s = s.deleteCharAt(i);
s = s.insert(i, ch);
}
}
return s.toString();
}
public static boolean isAlreadyInWord(String secretWord, char ch) {
for (int i = 0; i < secretWord.length(); i++) {
if (ch == secretWord.charAt(i)) {
return true;
}
}
return false;
}
}
The code works fine but I just have an issue with the capitalization.
If your speculation be correct, the comparing the lowercase of both sides of the equation should fix the problem:
if (Character.toLowerCase(ch) == Character.toLowerCase(secretWord.charAt(i)) {
return true;
}
Better yet, you can lowercase the user character input when it actually happens:
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().toLowerCase().charAt(0);
There are some handy functions in the Character class that you can use (Character.toUpperCase() and toLowerCase()) that can help you compare whether the characters match.
if (Character.toLowerCase(ch) == Character.toLowerCase(word.charAt(i)) && s.charAt(i) == '*') will always be checking two lowercase letters, so the case of neither ch or word.charAt(i) will matter.
When the code runs and you ask for char and type a letter lets say 'e' the output makes it "eeeee" instead of filling in the e's in the partial word method. I'm not sure how to fix it. I think the problem is either in replaceChar method or the updatePartialWord method. Would love some help. Thanks!
P.S i need to keep the method inputs the same even if there is an easier way!
// creates partialWord using string length then creating a new string with the same amount of dashes
public static String createPartialWord(String secretWord)
{
String newsecretWord = "";
int wordLength = secretWord.length();
while (wordLength > 0)
{
newsecretWord = newsecretWord + "-";
//System.out.print("-");
wordLength--;
}
System.out.println();
return newsecretWord;
}
//replaces character at certain ints
public static String replaceChar(String word, char c, int i)
{
//return word.replace(word.charAt(i), c);
String newText = word.replace(word.charAt(i), c);
return newText;
}
public static String updatePartialWord(String partial, String secret, char c)
{
if(c==secret.charAt(0))
{
return replaceChar(partial, c, 0);
}
if(c==secret.charAt(1))
{
return replaceChar(partial, c, 1);
}
if(c==secret.charAt(2))
{
return replaceChar(partial, c, 2);
}
if(c==secret.charAt(3))
{
return replaceChar(partial, c, 3);
}
if(c==secret.charAt(4))
{
return replaceChar(partial, c, 4);
}
return partial;
}
//Prints hangman
public static void printHangman(int guessLeft)
{
String HEAD = " ";
String BODY = " ";
String LEGS = " ";
String LEFTARM = " ";
String RIGHTARM = " ";
System.out.println("_____");
System.out.println("| |");
if (guessLeft < 6) {
HEAD = "()";
}
System.out.println("| " + HEAD);
if (guessLeft < 5) {
BODY = "||";
}
if (guessLeft < 4) {
LEFTARM = "\\";
}
if (guessLeft < 3) {
RIGHTARM = "/";
}
System.out.println("| " + LEFTARM + BODY + RIGHTARM);
if (guessLeft < 2) {
LEGS = "/";
}
if (guessLeft < 1) {
LEGS += "\\";
}
System.out.println("| " + LEGS);
System.out.println("|_____\n\n\n\n");
}
public static String generateSecretWord()
{
String[] names = { "alone", "apple", "anode", "abuse", "angle", "amaze","adobe","amuse",
"avoid","peter","sound","doubt","upper","lower","layer","enter","alter","boxer",
"faced", "alive","adore","names","voice","water","plate","pepsi","pizza","paste",
"hello","sugar","money","paper","while","times", "mouth","other","agile","again",
"acute","arise","argue","ankle","badge","blaze","bride","chase","sense","craze",
"dance","false","exile","drove"};
String name = names[(int) (Math.random() * names.length)];
return name;
}
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
String secretWord = generateSecretWord();
String partialWord = createPartialWord(secretWord);
System.out.println(" Welcome to HangMan");
System.out.println("I picked a secret word");
System.out.println();
//start for statement for main game
System.out.println("The current Partial Word is: " + partialWord);
for(int i = 6;i>0;)
{
System.out.println("The current Hangman picture is");
printHangman(i);
System.out.println("Player 2, you have " + i + " remaining guesses");
System.out.println("Would you like to guess the secret work or guess a character?");
System.out.println("Type \"word\" for word, type \"char\" for character");
String playerInput = stdin.nextLine();
String charInput = "char";
String wordInput = "word";
if(playerInput.equals(charInput))
{
System.out.println("Please type a character");
char input = stdin.nextLine().charAt(0);
if(secretWord.charAt(0)== input || secretWord.charAt(1)== input || secretWord.charAt(2)== input ||
secretWord.charAt(3)== input || secretWord.charAt(4)== input)
{
System.out.println("That character is in the secret word");
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
}
else
{
System.out.println("Sorry that charcater is not in the secret word");
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
if(i==1)
{
System.out.println("You've killed the hangman. You've lost the game");
printHangman(0);
break;
}
i--;
}
}
else
{
System.out.println("Please guess the word");
String userGuess = stdin.nextLine();
if(userGuess.equals(secretWord))
{
System.out.print("Congrats that is the secret word! You've won the game!");
System.out.println("Here is the hangman");
printHangman(i);
break;
}
else
{
System.out.println("Sorry thats not the secret word. You've lost.");
break;
}
}
}
}
}
public static String replaceChar(String word, char c, int i) {
String newText = word.replace(word.charAt(i), c);
:
The word in this case is -----, so you are replacing all occurrences of the character at position i (which is -) with the letter.
So all - characters are becoming the character you just entered.
You should instead be changing each character in the partial word, if and only if the equivalent character in your secret word matches the character just entered, something like:
public static String replaceChar(String word, String secret, char c) {
for (int i = 0; i < word.length(); i++) {
if (secret.charAt(i) == c) {
word = word.substring(0, i) + c + word.substring(i+1);
}
}
return word;
}
Of course, since you're now using the secret word and the position of the character is irrelevant, you change what gets passed in. The calling code can be modified to be:
if (c == secret.charAt(0))
return replaceChar(partial, secret, c);
if (c == secret.charAt(1))
return replaceChar(partial, secret, c);
// :
// and so on.
Of course, even with that fix, you still have a problem:
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
This outputs the new partial word as calculated by the function but it doesn't actually change the partial word. You need something along the lines of:
partialWord = updatePartialWord(partialWord, secretWord, input));
System.out.println("The current partial word is: " + partialWord);
As per the javadocs
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
I am trying to make a text-based Hangman in Java.
This is my Java code:
package hangman;
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class Hangman {
public static void main(String[] args) {
// TODO code application logic here
Scanner chez = new Scanner(System.in);
Scanner waffle = new Scanner(System.in);
Random randomGenerator = new Random();
StringBuilder displayWord = new StringBuilder("______________________________");
String theWord = null;
String preLetter;
//String sbDisplayWord;
char letter = 0;
int randomNumber;
int lengthOfWord;
int numberOfLetterInWord = 0;
int gDisplay;
int guessWordNumber = 0;
String guessWord;
RandomWord troll = new RandomWord();
randomNumber = randomGenerator.nextInt(12);
//Fill var with the word.
theWord = troll.wordDecide(randomNumber);
System.out.println ("Welcome to Hangman!");
lengthOfWord=theWord.length( );
System.out.println("This word has " + lengthOfWord + " letters.");
System.out.println("You have 20 guesses.");
for (int g =19; g >= 0; g--) {
System.out.println("If you want to guess the word, type 0. If you want to guess a letter, type 1.");
guessWordNumber=chez.nextInt();
if (guessWordNumber==0) {
System.out.println("Enter the word now. Remember, don't capitalize it.");
guessWord=waffle.nextLine();
if (guessWord.equals(theWord)) {
System.out.println("YOU WIN");
System.exit(0);
} else {
System.out.println("Sorry, this wasn't the correct word.");
}
} else if (guessWordNumber==1) {
System.out.println("Please enter the letter you wish to guess with.");
//System.out.println("It will tell you if you have guessed right for any of the letters. If it is blank, that means none of the letters match.");
preLetter=chez.nextLine();
letter=preLetter.charAt(0);
System.out.println("");
for(int i = 0; i <= lengthOfWord -1; i++ ) { //-Eshan
if (letter == theWord.charAt( i )) {
numberOfLetterInWord=i+1;
System.out.println("This letter matches with letter number " + numberOfLetterInWord + " in the word.");
displayWord.setCharAt(i, letter);
} else {
numberOfLetterInWord=i+1;
System.out.println("This letter doesn't match with letter number " + numberOfLetterInWord + " in the word.");
}
}
System.out.println("");
System.out.println("The word so far is " + displayWord);
System.out.println("");
gDisplay = g + 1;
System.out.println("You have " + gDisplay + " guesses left.");
} else {
System.exit(0);
}
}
System.out.println("GAME OVER");
System.exit(0);
}
}
package hangman;
public class RandomWord {
private static String[] wordArray = {
"psychology",
"keratin",
"nostalgia",
"pyromaniac",
"chlorophyl",
"derivative",
"unitard",
"pterodactyl",
"xylophone",
"excommunicate",
"obituary",
"infinitesimal",
"concupiscent",
};
public String wordDecide(int randomNumber) {
String theWord;
theWord = wordArray[randomNumber];
return theWord;
}
}
Netbeans is giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at hangman.Hangman.main(Hangman.java:56)
Java Result: 1
This is probably happening when you call charAt(0) on a string of length 0. You should check to see that the string is not empty before calling the method.
You are getting a StringIndexOutOfBoundsException due to the fact the line
guessWordNumber = chez.nextInt();
does not consume newline characters and passes the character through to the line
preLetter = chez.nextLine();
which then doesn't block as it will have already received input. This assigns an empty String to preLetter resulting in the exception. You can use Scanner#nextLine to consume this character:
guessWordNumber = Integer.parseInt(chez.nextLine());