This question already has answers here:
Java ternary (immediate if) evaluation
(3 answers)
Closed 7 years ago.
I recently got help writing a statement checking if input text was blank or only whitespace. I got it working but do not really understand the code since its too advanced refactoring for me. Could someone please translate this to more basic code?
name = name == null ? "" : name.trim();
Your code is similar to:
String name = //your input
if(name==null) {//if name si null
name = "";//assign empty string
} else {
name = name.trim(); //remove leading and trailing whitespace
}
The if else is replace with "? :" operator
The thing you are seeing is a "ternary operator". It follows this syntax:
boolean ? ifTrue : ifFalse
Ternary operators do not work quite like if/else statements: They provide you with a value (like 3 + 4).
So in this example, you set name to the result of the following ternary expression:
is name null? -+- true --> ""
|
+- false -> name.trim() (this function removes whitespace at
the beginning and at the end of the string)
You could also write:
public static String parseName(String name)
{
if (name == null)
return "";
//else (else not neccesary here)
return name.trim();
}
// in some block...
name = parseName(name);
if name is equal to null it will be equal to "";
else it will be equal to name.trim()
name = name == null ? "" : name.trim();
that means
String name;
//You performed some processing here, your logic.
if(name==null){
name="";
}
else{
name=name.trim();
}
Related
This question already has answers here:
How to trim the whitespace from a string? [duplicate]
(8 answers)
Closed 4 years ago.
I'm working on a Registration UI and it checks if the user already exists in the database, the program works fine and all, but i have received bug reports that if you add whitespace at the start or end of the name you entered, it will assume its a new name and won't be blocked by detecting that the name already exists.
String name = txfUName.getText();
If(this.checkIfNameExists(name) == true);
{
...
}
else
{
...
}
How would I check if the first and last character is a whitespace (in a loop)
and replace that whitespace with an empty string "" until there are no whitespaces in front or at the back of the name, assume the name can contain whitespaces in between words.
A very easy standard Java method from String - trim(). It removes leading and trailing white-space characters.
String name = txfUName.getText();
name = name.trim();
Or simply:
String name = txfUName.getText().trim();
Also, make sure getText() doesn't return null. If it does - implement a null check before calling trim().
Please use string trim function
String name = txfUName.getText();
name = name.trim();
If(this.checkIfNameExists(name) == true); {
...
} else {
...
}
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'.");
}
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
I've been trying to Google it, but googling the key "?" doesn't really work out that good.
I really want to know what it does and when to use it.
Thanks!
I've seen it a couple times, but here is an example of one I just saw
String name = perms.calculateRank().getColor() + player.getName();
//This is a custom ranking system ^
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
player.setDisplayName(name + ChatColor.RESET);
Chat.sendMessage(player, "Tab Name Set");
This is a ternary operator. In Java specifically, it is called the Conditional Operator. It is a way of writing short-hand simple if..else statements. For example:
if (a == b) {
c = 123;
} else {
c = 456;
}
is the same as:
c = a == b ? 123 : 456;
It is also used for a wildcard generic.
public List<?> getBizarreList();
The ternary operator someBoolean ? x : y evaluates to x if someBoolean is true, and y otherwise.
It is called ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format
General Syntax :
boolean expression ? value1 : value2
your example:
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
as same as
if( name.length() > 15)
player.setPlayerListName(name.substring(0, 16));
else
player.setPlayerListName(name);
This question already has answers here:
Strange Null pointer exception case: ternary conditional operator not working with string concatenation
(6 answers)
Closed 6 years ago.
how can i get null pointer exception from this line of code?
String a = "localUri: "+ mCurrentImageUri == null? "none" : mCurrentImageUri.toString();
mCurrentImageUri == null, but I have thought it won't evaluate mCurrentImageUri.toString() if so
half-related:
how to write similar to this c# syntax?
string a = myVar?? "none"
You need parentheses:
"localUri: " + (mCurrentImageUri == null ? "none" : mCurrentImageUri.toString())
Without parentheses, it's parsed as (("localUri: "+ mCurrentImageUri) == null) ? ..., which is always false.
As to the Java code, as others pointed out,
what you have written in Java is equivalent to:
String a = ("localUri: " + mCurrentImageUri == null ) ? "none" : mCurrentImageUri.toString();
and that's why you get the NullPointerException (NPE).
In C# you can just do:
myVar == null ? "none" : myVar.ToString()
The syntax is quite similar to Java
( in Java you have toString(), in C# you have ToString() )
In C#, as you suggested, you can also use the
left coalesce operator. For more details, check here:
http://msdn.microsoft.com/en-us/library/ms173224.aspx
how can i get null pointer exception from this line of code?
If you look the table operators precedence + has a higher precedence than the ternary operator, so you concatenate your string first then it's not null so you go in the second condition.
I know you can have
String answer = (5 == 5) ? "yes" : "no";
Is it somehow possible to have only:
String answer = (5 == 5) ? "yes";
It gives a compile error when I try.
NOTE: (5==5) is just an example. In its place will be statement which could be either true or false.
if one line is important
String answer = (5 == 5) ? "yes": null;
Since a String's default value is null.
You're looking for an if statement:
if (5 == 5)
answer = "yes";
Your idea is impossible because an expression (such as the conditional value) must always have a value.
In your code, if 5 != 5, the expression would have no value, which wouldn't make any sense.
No. you can't have it. You need to specify both the ? and :.
Use a straight if.