Check if an character is an operator [duplicate] - java

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 == '-'){

Related

How to change string to lower case? [duplicate]

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.

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, '*');

Exception in thread "main" java.util.NoSuchElementException in if statem [duplicate]

This question already has answers here:
Scanner NoSuchElementException when calling .next() method
(3 answers)
Closed 5 years ago.
if (charIte.next()=='{' || charIte.next()=='}'
|| charIte.next()=='[' || charIte.next()==']'
|| charIte.next()=='(' || charIte.next()==')'
|| charIte.next()=='*' || charIte.next()=='"'
|| charIte.next()=='/'){
}
The program returns:
Exception in thread "main" java.util.NoSuchElementException at line
|| charIte.next()=='(' || charIte.next()==')'
What is the problem?
Each invocation of next() consumes one token. Call it once, and save and then compare with the result. Like,
char ch = charIte.next();
if (ch == '{' || ch == '}' || ch == '[' || ch == ']' || ch == '('
|| ch == ')' || ch == '*' || ch == '"' || ch == '/') {
// ...
}
Each time you do charIte.next() you're asking to read the next token.
I think what you should do to ischar ite = charIte.next.chartAt(0) and then use ite in your if statement
if (ite next()=='{' || next()=='}'
|| ite.next()=='[' || ite.next()==']'
|| ite.next()=='(' || ite.next()==')'
|| ite.next()=='*' || ite.next()=='"'
|| ite.next()=='/'){
Info on Scanner

Validate a string contains only certain characters in java

Ok, what I am trying to do is take a user input in infix notation and translate it to postfix and then evaluate it. I have that already completed.
What I am struggling with, is for the user input I need to validate that it only contains the following: (), 0-9, +, -, *, /, %
Each character will be separated by a space, so here is a potential valid input:
( 3 + 4 ) * 5 / ( 6 - 7 )
I have created an InvalidCharacterException that I wish to throw if the user string contains anything other than those characters.
Here is what an invalid input would look like:
3 - 5 ^ 5
The ^ would be an invalid character and then I would throw new InvalidCharacterException and ask for a new input.
I will also say I have looked at a ton of regex samples, and to be honest I don't understand what they're doing.
EDIT:
Ok, this is what I ended up implementing because I don't really understand anything else. Any advice on a simpler way?
for(int i = 0; i <= infix.length(); i++){
if(infix.charAt(i) == '(' || infix.charAt(i) == ')' || infix.charAt(i) =='+'
|| infix.charAt(i) =='-' ||infix.charAt(i) == '*' ||infix.charAt(i) == '/'
||infix.charAt(i) == '%' ||infix.charAt(i) ==' ' ||infix.charAt(i) == '0'
||infix.charAt(i) == '1' || infix.charAt(i) =='2' || infix.charAt(i) =='3'
||infix.charAt(i) == '4' ||infix.charAt(i) == '5' ||infix.charAt(i) == '6'
||infix.charAt(i) == '7' || infix.charAt(i) =='8' ||infix.charAt(i) == '9'){
}else{
throw new InvalidCharacterException(infix.charAt(i));
}
}
Infix is the variable name of my user input as a StringBuffer.
You can use a Scanner to validate your string:
Scanner scanner = new Scanner(string);
String validationResult = scanner.findInLine("[^0-9()+\\-*\\/%]+");
if (validationResult != null) {
// Invalid character found.
throw new InvalidCharacterException("Invalid character: " + validationResult);
}
The findInLine method returns a String with the characters that match the regex and the regex looks for any character not valid in your validation. The findInLine only returns a non null String when there are any invalid characters in the String.
I would suggest you use a Scanner (for an example) and then loop over each character (in each token) and throw your Exception if your criteria are met (e.g. look at Character.isDigit) or just write your own method to test against acceptable characters (e.g. is char is contained in"()0123456789+-*/%").
In your code this is probably better because it does the same thing.
Btw it probably should be i < infix.length() not <=
for(int i = 0; i < infix.length(); i++){
char x = infix.charAt(i);
if(!(Character.isDigit(x) || x == '/' || x == '*' ||
x == '+'|| x== '-' || x=='%' || x == '\n'))
throw new InvalidCharacterException(x);
/* what you want to do if valid*/
}

Checking for special characters and spaces

I have a hangman game created in java. I want to create a simple function that will check if the word input has white space and/or special characters.
I've found the functions String.replaceAll(), but I haven't been able to dig up a premade function that returns a boolean value for if there are special charactors and/or white space.
Is there a function out there already? Or at least a simpler way of specifying no white space or special characters other than doing the following?
public void checkWord()
{
boolean flag = false;
for(int i=0;i<wordArray.length;i++)
{
if(wordArray[i] == '1' || wordArray[i] == '2' || wordArray[i] == '3' || wordArray[i] == '4' || wordArray[i] == '5' || wordArray[i] == '6' || wordArray[i] == '7' || wordArray[i] == '8' || wordArray[i] == '9' )
{
flag = true;
}
}
if(flag == true)
{
System.out.println("Invalid characters used in the word");
System.exit(0);
}
}
The function is getting dense, and I've only covered digits. Thoughts?
You can use a simple regular expression:
public boolean isValidWord(String w) {
return w.matches("[A-Za-z]*");
}
Explanation of the regex:
[A-Za-z] - capital or lowercase letter
* - zero or more
More info on regexes: http://www.regular-expressions.info/

Categories

Resources