How to change string to lower case? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Trying to make it so that if the user enters any vowel capitalized, it will return true. So, that's where I added the "letter = letter.toLowerCase();" but it's not working still..
public static boolean isVowel (String letter) {
letter = letter.toLowerCase();
if (letter == "a" || letter == "e" || letter == "i" || letter == "o" || letter == "u" ) {
return true;
} else {
return false;
}
}

Try using if (letter.equals("a") || and so on.
== tests the memory references of String variables, not the contents of the references.
The equals method of the String class tests the contents of the references.

Related

If statement not recognizing user input [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
public static void getSolve(Scanner s) {
boolean validInput = false;
while(validInput == false) {
System.out.println("Would you like to try to solve the word? (yes or no)");
String input = s.nextLine();
if(input == "yes" || input == "Yes") {
validInput = true;
System.out.println("Enter your full guess: ");
String guess = s.nextLine();
if (guess == secretWord) {
System.out.println("You guessed the word!");
displayString = secretWord;
}
else {
System.out.println("Sorry, that is not the word");
NUM_LIVES --;
}
}
else if (input == "no" || input == "No") {
validInput = true;
}
else {
System.out.println("Sorry, that is not a valid input");
}
}
}
This is the code that I am using for a solve method for a java project for my class in which I am coding a hangman game. I am trying to add a feature that asks the user if they would like to try to solve the word and then checks to see if they got that guess correct. Right now what is happening is that no matter what the user puts in, even if it is "yes" or "no", the program thinks that it is an invalid input and asks the question again, putting the code into an infinite loop. I'm not quite sure how to fix this and I'm not sure what I am doing wrong. Any help is greatly appreciated!
Looks good to me except this one:
input == "yes" || input == "Yes"
should be
"yes".equalsIgnoreCase(input)
And others:
guess == secretWord -> guess.equals(secretWord)
input == "no" || input == "No" -> "no".equalsIgnoreCase(input)
You need to compare strings using .equals in java.
if(input.equals("yes") || input.equals("Yes"))
You can also use .equalsIgnoreCase() so you don't have to write all forms of the word yes.
.equals() is used to compare objects.

Check if an character is an operator [duplicate]

This question already has answers here:
If statement, compare one variable to multiple [duplicate]
(6 answers)
Is there a simpler way to check multiple values against one value in an if-statement? [duplicate]
(12 answers)
Comparing chars in Java
(13 answers)
is it possible to check if a char matches a list of possibilities?
(4 answers)
How can I compare char characters?
(1 answer)
Closed 4 years ago.
I want to check if a character is an operator like : %,/,*,+,-
This is the code to get input from the user in the main function:
Scanner input = new Scanner(System.in);
System.out.println("Operator (S is stoppen)");
String operator = input.nextLine();
char o = operator.charAt(0);
So the input is stored in the variabele 'o'
So now I tried to make a new function to check if the character is one of these functions: %,/,*,+,-
this is the function I tried to make:
static boolean isGeldigeOperator(char o) {
if (o == '%' || '/' || '*' || '+' || '-'){
return true;
} else{
return false;
}
So if o == one of the operators return true and if not return false.
Now the error that I'm getting is about this line:
if (o == '%' || '/' || '*' || '+' || '-'){
Its this error: Operator || cannot be applied to 'boolean', 'char'
Does anyone know what I'm doing wrong?
This line:
if (o == '%' || '/' || '*' || '+' || '-'){
should be:
if (o == '%' || o == '/' || o == '*' || o == '+' || o == '-'){

Error when trying to get a character in a string replaced [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
How to replace replace vowels with a special character in Java?
(5 answers)
Closed 5 years ago.
For my program I am trying to replace all the vowels in a word with asterisk. I have written the code but keep receiving an error in the line where I am trying to replace the letter. The error I receive is " cannot find symbol" can someone explain to me why I am receiving this error?
for(int index =0; index<=length;index++){
Character vowel = firstName.charAt(index);
if ((vowel == 'A') || (vowel == 'a') || (vowel == 'E') || (vowel == 'e') || (vowel == 'I') || (vowel == 'i')
|| (vowel == 'O') || (vowel == 'o') || (vowel == 'U') || (vowel == 'u')){
vowel = vowel.replace( vowel, '*'); // error received here
}
}
why don't you just do :
firstName = firstName.replace(firstName.charAt(index), '*');
or
firstName = firstName.replace(vowel, '*');
I would prefer a single regular expression to your loop logic, and you might use ?i to ignore case. Basically, match any vowel and replace with an asterisk. Like,
String firstName = "David";
System.out.println(firstName.replaceAll("(?i)[aeiou]", "*"));
Outputs
D*v*d
vowel is of typ Character and does not have a .replace method. Not exactly sure what you want to achive but you might want to replace the char in firstname:
firstname.replace( vowel, '*');

So I need to find all vowels in a string and replace them using a loop

So I have this and be aware that I only use simple methods such at toString(), charAt. Right now my code is just returning the original string, and I do not know why.
Ok, so I realized that after a few tests, the reason it is returning the original string is because in the nested if statement in the loop, the condition is never true, so it bypasses the if statement. Why is it never true?
System.out.print("Enter in a string: ");
String userInput = scan.nextLine();//string user enters
String vowelChar;//individual character within user's input
for (int i=0; i<userInput.length(); i++){
Character indChar = userInput.charAt(i);
vowelChar = indChar.toString();
if (vowelChar=="a" || vowelChar=="e" || vowelChar=="i" || vowelChar=="o" || vowelChar=="u"){
String beforeText = userInput.substring(0, i-1);//string before vowel
String afterText = userInput.substring(i+1);//string after vowel
userInput=beforeText+"_"+afterText;
}else{
//character is not a vowel
//do nothing
}
}
System.out.print(userInput);
}
}
A few things to consider:
Don't use "==" when comparing Strings, as explained in: Why doesn’t == work on String?
You can compare chars with "==", so you shouldn't need to convert it to a String for the comparison.
The index in your for loop starts at 0, so this statement:
String beforeText = userInput.substring(0, i-1)
will throw a java.lang.StringIndexOutOfBoundsException if there is a vowel at the first index.
You don't need the "else" case if you aren't doing anything inside it.
Although this isn't how I would implement the kind of loop you wanted, here is a solution that works with the least amount of changes to your original code:
System.out.print("Enter in a string: ");
String userInput = scan.nextLine();//string user enters
for (int i = 0; i < userInput.length(); i++) {
Character indChar = userInput.charAt(i);
if (indChar == 'a' || indChar == 'e' || indChar == 'i' || indChar == 'o' || indChar == 'u' ||
indChar == 'A' || indChar == 'E' || indChar == 'I' || indChar == 'O' || indChar == 'U') {
String beforeText = userInput.substring(0, i); //string before vowel
String afterText = userInput.substring(i + 1); //string after vowel
userInput = beforeText + "_" + afterText;
}
}
System.out.print(userInput);
Instead of converting back to String and comparing with == (since we compare the value of Strings via Object#equals), use the char type for your comparison using if/switch. Additionally you should compare in a singular casing so as not to have A and a not match.
char c = Character.toLowerCase(userInput.charAt(i)); //make the character lowercase
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
//replace vowel
break;
}
There is no need to convert to a String. Compare characters directly
Character indChar = userInput.charAt(i);
if ((vowelChar == 'a' || vowelChar == 'e' || vowelChar == 'i' || vowelChar=='o' || vowelChar=='u') {
// ...
}
Note the char in single quotes and not double quotes
Change your code like this
if (vowelChar.equals("a") || vowelChar.equals("e") || vowelChar.equals("i") || vowelChar.equals("o") || vowelChar.equals("u")){
Or
if (indChar =='a' || indChar =='e' || indChar =='i' || indChar =='o' || indChar =='u'){
String a = "abcde";
Character indChar = a.charAt(0);
String vowelChar = indChar.toString();
System.out.println("vowelChar Char: " + vowelChar);
System.out.println(vowelChar == "a"); printed false
System.out.println(vowelChar.equals("a")); printed true
So use equals instead of ==

Issue with or operator in Java - ||

I'm writing a password validation program and having some issues with the or statement that checks for special characters. I'm not sure what is wrong with it, the rest of the program seems to function properly, but entering a password that matches the criteria, for example, P#ndas123$%, just results in an infinite loop.
I believe that the problem is related to my big statement for the !pass.contains("") portion. If that is right, could someone help me understand why the statement is incorrect?
import java.util.Scanner;
public class DylanJacksonProg5 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
boolean valid;
valid = true;
do {
//Password rules declared to user
System.out.println("Password Verifier");
System.out.println("");
System.out.println("Enter a password that meets the following rules: ");
System.out.println(" Is at least 8 characters long");
System.out.println(" Contains at least 1 lower letter character");
System.out.println(" Contains at least 1 upper letter character");
System.out.println(" Contains at least 1 numeric digit");
System.out.println(" Contains at least 1 special character of the following set: !##$%^&*");
System.out.println(" Does not contain the word 'and' or the word 'the'");
//Gathering password from user
System.out.println("Enter your password: ");
String pass;
pass = user_input.next();
//Validating password to rules
if (pass.length() < 8) {
int shortlen;
shortlen = 8 - pass.length();
System.out.println("Password is too short. Please add " + shortlen + " characters");
valid = false;
} else
System.out.println("Password length is acceptable.");
//Check for character cases
boolean hasUppercase = !pass.equals(pass.toLowerCase());
boolean hasLowercase = !pass.equals(pass.toUpperCase());
if (!hasUppercase) {
System.out.println("Must have an uppercase Character");
valid = false;
}
if (!hasLowercase) {
System.out.println("Must have a lowercase Character");
valid = false;
}
if (hasUppercase) {
System.out.println("Has an upper case character");
}
if (hasLowercase) {
System.out.println("Has a lowercase Character");
}
//Check for digit
for (int i = 0; i < pass.length(); i++) {
char x = pass.charAt(i);
if (!Character.isDigit(x)) {
valid = false;
}
}
//check for special character
if (!pass.contains("!") || !pass.contains("#") || !pass.contains("#") || !pass.contains("$") ||
!pass.contains("%") || !pass.contains("^") || !pass.contains("&") || !pass.contains("*"))
{
valid = false;
System.out.println("Password requires a special character from the following: !##$%^&*");
}
// check for 'and'
if (pass.contains("and")) {
valid = false;
System.out.println("Cannot contain 'and'");
}
//check for 'the'
if (pass.contains("the")) {
valid = false;
System.out.println("Cannot contain 'the'");
}
System.out.println("");
}
while (!valid);
}
}
I'll tell you one problem straight up front.
Since you set valid to true before the validation loop, and only ever set it to false within the loop, entering an invalid password as your first attempt will result in the loop never exiting.
The setting of valid to true should be the first thing done within the loop.
On top of that, your checks each individually apply to every character in the input string, a situation which is impossible. For example, you check whether the entire string is equal to its lowercased variant, then you check whether it's also equal to its uppercased variant.
That means any string with a letter in it will be deemed invalid since xyZZy cannot be equal to both xyzzy and XYZZY at the same time.
It would be more correct to do something like (pseudo-code, and cut down to a few conditions just to show the method):
do:
hasLowercase = false
hasUpperCase = false
hasNumeric = false
isLongEnough = false
get string from user
if len(string) >= 8:
isLongEnough = true
for each character in string:
if character is lowercase:
hasLowerCase = true
if character is uppercase:
hasUpperCase = true
if character is numeric:
hasNumeric = true
isValid = hasLowerCase && hasUpperCase && hasNumeric && isLongEnough
until isValid
This checks each individual character so that any of them (rather than requiring that all of them) will mark a condition as true.
The OR operators will conflict if you don't have all of the special characters in the password, because in your condition statements, if you have "!" but not "#", it will still result in a false value.
What you can do is check for each special character separately.
Sorry for the lack of explanation, but it is your negation statements in your special character checking block. Usually using !condition works, but it didn't on this online IDE I am using. Not really sure why.
This code will work:
//check for special character
if (pass.contains("!") || pass.contains("#") || pass.contains("#") || pass.contains("$") ||
pass.contains("%") || pass.contains("^") || pass.contains("&") || pass.contains("*"))
{
valid = true;
System.out.println("Password requires a special character from the following: !##$%^&*");
}
else
{
valid = false;
}
There are multiple problems with your code, which are unrelated to each other:
You never set valid to true in the loop, which means that if you enter 1 wrong password, valid will be and always stay false, which means that no matter how many correct passwords you enter afterwards, the loop will repeat infinitely. In other words: the program will only stop if you enter a correct password at the very first attempt.
The big boolean expression is not checking whether the password contains any of the characters, it is checking whether the password contains all characters. Draw the truth table or apply DeMorgan's Laws, and you will see:
!p.c("!") || !p.c("#") || !p.c("#") || !p.c("$") || !p.c("%") || !p.c("^") || !p.c("&") || !p.c("*")
// is the same per DeMorgan's Laws as
!(p.c("!") && p.c("#") && p.c("#") && p.c("$") && p.c("%") && p.c("^") && p.c("&") && p.c("*"))
As soon as you find a single character that is not a digit, you reject the password, IOW all characters must be digits.
It should be obvious that #2 and #3 contradict each other, so it it simply impossible to enter a valid password, so even if you fix #1, it will still not be possible to exit the loop.
There are a 3 issues with your code:
valid must be set to true inside your loop before any checks are done on input:
do {
valid = true;
...
lower & upper case checks should be done differently, for example:
boolean hasUppercase = false;
boolean hasLowercase = false;
for (int i = 0; i < pass.length(); i++){
if (Character.isUpperCase(pass.charAt(i))){
hasUppercase = true;
}
if (Character.isLowerCase(pass.charAt(i))){
hasLowercase = true;
}
}
your checks for special character are incorrect, you could use below instead:
if (!(pass.contains("!") || pass.contains("#") || pass.contains("#") || pass.contains("$") || pass.contains("%") || pass.contains("^") || pass.contains("&") || pass.contains("*"))){
valid = false;
}
EDIT: actually there's another one:
4. Your check for digit also won't work, you could use below instead:
boolean isDigit = false;
for (int i = 0; i < pass.length(); i++) {
char x = pass.charAt(i);
if (Character.isDigit(x)) {
//valid = false;
isDigit = true;
break;
}
}
if (!isDigit)
valid = false;
Here's how OR operator works:
if( condition1 || condition2 || condition3 || condition4)
{
// .....your code;
}
If condition1 is true,then remaining conditions will not be checked and program will move to inside your IF block.However,if Condition1 is false,then condition2 will be checked.If this is true,then remaining conditions will not be checked,otherwise(if it is false) condition3 will be checked.and so on.However as other peoples have already mentioned there is more problem with your code than just with OR operator.
For example,for password=P#ndas123$%,it does not contain "!",so !pass.contain("!") will give true and valid will be set as false thus causing infinite loop.

Categories

Resources