Java - using ".contains" in the opposite manner - java

I want to be able to print a string that doesn't contain the words "Java", "Code" or "String", though I am unsure on how to achieve this as I thought this would be achieved by using '!' (NOT). However, this is not the case as the string is still printed despite the inclusion of the words I want to forbid.
Any advice on how to achieve this would be greatly appreciated, thanks in advance.
System.out.println("Type in an input, plez?");
String userInput6 = inputScanner.nextLine();
if (!userInput6.toLowerCase().contains("Java") || !userInput6.toLowerCase().contains("Code") || !userInput6.toLowerCase().contains("String")) {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
} else {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
}

I thought this would be achieved by using '!' (NOT)
It is. You just haven't applied it correctly to your situation:
You start with this statement:
userInput6.toLowerCase().contains("java") ||
userInput6.toLowerCase().contains("code") ||
userInput6.toLowerCase().contains("string")
which checks if the input contains any of these, and you wish to negate this statement.
You can either wrap the entire statement in parentheses (()) and negate that:
!(userInput6.toLowerCase().contains("java") ||
userInput6.toLowerCase().contains("code") ||
userInput6.toLowerCase().contains("string"))
or apply the DeMorgan's law for the negation of disjunctions which states that the negation of a || b is !a && !b.
So, as Carcigenicate stated in the comments, you would need
!userInput6.toLowerCase().contains("java") &&
!userInput6.toLowerCase().contains("code") &&
!userInput6.toLowerCase().contains("string")
instead.
Your statement is simply checking if the string doesn't contain at least one of these substrings. This means the check would only fail if the string contained all of these strings. With ||, if any operand is true, the entire statement is true.
Additionally, mkobit makes the point that your strings you are checking for should be entirely lowercase. Otherwise, you are checking if a .toLowerCased string contains an uppercase character - which is always false.
An easier way to think of it may be to invert your if statement:
if (userInput6.toLowerCase().contains("Java") ||
userInput6.toLowerCase().contains("Code") ||
userInput6.toLowerCase().contains("String")) {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
} else {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
}

Since you're using logical OR, as soon as one your contains checks it true, the entire condition is true. You want all the checks to be true, so you need to use logical AND (&&) instead
As #mk points out, you have another problem. Look at:
userInput6.toLowerCase().contains("Java")
You lower case the string, then check it against a string that contains an uppercase. You just removed all uppercase though, so that check will always fail.

Also, you can use regexp :)
boolean notContains(String in) {
return !Pattern.compile(".*((java)|(code)|(string)).*")
.matcher(in.toLowerCase())
.matches();
}
Or just inline it:
System.out.println("Type in an input, plez?");
String userInput6 = inputScanner.nextLine();
if (!Pattern.compile(".*((java)|(code)|(string)).*")
.matcher(userInput6.toLowerCase())
.matches()) {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
} else {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
}

Related

Java if statment contains letters

I was wondering how I should write this if statement in my assignment.
The question is:
Print option 2 if one of the strings begins with the letter w or has 5 characters.
I would use the .contains to find the "w".
if (two.contains("w") {
System.out.println(two);
but the one with the characters I am unsure how to find the method.
If you have a List or Set, you may need to loop over them one by one, to do the actual comparing try this:
(two.startsWith("w") || two.length() == 5) {
System.out.println(two);
}
The first condition checks if given String object starts with given char, and the other one counts the number of characters in the String and checks your desired lenght, which is 5.
For more useful information and String object has, check this out String (Java Platform SE 7)
String aString = ".....";
if (aString.startsWith("w") || aString.length() == 5) {
System.out.println("option 2");
}
The method .contains returns true if find a substring (in this case "w") in string. You should use .startsWith method.

How to put 2 condition in one statement actiolistener in java? [duplicate]

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}

I'm getting a operator undefined error when I use ||

I'm trying to get the code to check if an input either has nothing and is entered or doesn't have either Y or N, but I keep getting an error.
I've tried using just " | " but that doesn't work, and " , " just doesn't make sense.
while (answerToFirstQuestionYN.isEmpty() && !answerToFirstQuestionYN.equalsIgnoreCase("Y" || "N")) {
System.out.println("Input not recognized, try again.");
answerToFirstQuestionYN = reader.next();
}
The error message is " The operator "||" is undefined for the argument type(s) java.lang.String, java.lang.String "
The || operator can only join boolean expressions. So you need to separate the conditions to:
!(answerToFirstQuestionYN.equalsIgnoreCase("Y") ||
answerToFirstQuestionYN.equalsIgnoreCase("N"))
Your first condition (answerToFirstQuestionYN.isEmpty()) needs to be removed, otherwise the whole condition is only true if the string is empty.
Java is not natural language. In English, we can say "if answer is Y or N", where "or" can join noun phrases. In Java, "or" only applies to truth values; and expressions are evaluated as in math, with whatever is in parentheses first. answer.equals("Y" || "N") would try to evaluate "Y" or "N" first, which is, from Java's perspective, nonsense. What you really need to do is to first have two truth values: "if answer is Y, or if answer is N":
answer.equals("Y") || answer.equals("N")

Regex not valid when trying to invalidate alpha's and non-zeros

Wrote a method which takes in a String and checks to see the follow conditions:
If String is "quit", it will terminate the program.
If the String is any value other than an integer, it should return "Invalid input ".
Any negative integers and also 0 should return "Invalid input".
However, when I passed in 10, it returned as "Invalid input"?
Please advise:
public static String validate(String input) {
Pattern pattern = Pattern.compile(".*[^1-9].*");
StringBuilder results = new StringBuilder();
if (input.equals("quit")) {
System.exit(1);
} else if (!pattern.matcher(input).matches() == false) {
results.append("Invalid input ");
results.append("'");
results.append(input);
results.append("'");
}
return results.toString();
}
What's wrong with what I am doing?
You should write a pattern of what you expect instead of what you're not.
As describe what you want is always simpler that describe the rest of it.
So you expect :
Pattern acceptPattern = Pattern.compile("[1-9][0-9]*");
You may consider make you conditional expression simpler and correct by not using both ! and == false at the same time:
Which will make :
if (!acceptPattern .matcher(input).matches()) {//Invalid input code}
or
if (acceptPattern .matcher(input).matches() == false) {//Invalid input code}
note :
You write if(!A == false) => if(A == true) => if(A) but which was the inverse
It looks like you want to match one or more digits, where the first one is not a zero.
[1-9]\d*
If you want to force it to be the entire string, you can add anchors, like this:
^[1-9]\d*$
Your regex string doesn't allow for the presence of a zero (not just a lone zero).
That is, the string ".*[^1-9].*" is looking for "any number of characters, something that isn't 1-9, and any number of characters". When it finds the zero, it gives you your incorrect result.
Check out What is the regex for "Any positive integer, excluding 0" for how to change this.
Probably the most helpful solution on that page is the regex [0-9]*[1-9][0-9]* (for a valid integer). This allows for leading zeros and/or internal zeros, both of which could be present in a valid integer. In using Matcher#matches you also ensure that this regex matches the whole input, not just part of it (without the need to add in beginning and end anchors -- ^$).
Also, the line else if (!pattern.matcher(input).matches() == false) could be made a lot more clear.... maybe try else if (pattern.matcher(input).matches()) instead?

Do while loop comparing Strings

I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results

Categories