Hello!
If you enter a space when you receive the string (variable name word), you want to output true, false, depending on whether this string is blank or not.
If there is a space in the String, why can't I do branching in if(word.equals(")) System.out.println("blank");?
The source code we tested is as follows.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String word = br.readLine().trim();
if(word.equals(" ")) {
System.out.println ("blank");
}
else if(word.trim().length()==0) {
System.out.println ("Trim");
}
else if(word.equals(null)) {
System.out.println("null");
}
else {
System.out.println ("string: "+word+"string length:"+word.length()));
}
}
}
Thank you!
java string
String word = br.readLine().trim();
from trim ()
Removes a trim because it is to remove a space.
String word = br.readLine();
If you put in the space twice and type enter, it will be judged as blank.
If it were me, I'd revise it like this.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Remove String word = br.readLine(); //.trim() and check trim below
Method for verifying that if(word.isBlank()) { //word consists of only blank characters such as white space, tab, etc
System.out.println ("blank");
}
else if(word.trim().length()!=word.length()) { // true if removing a space before and after is different from the original string length
System.out.println ("Trim");
}
// else if(word.equals(null)) { //This if statement is meaningless. There is no null value because you assigned a string with br.readLine().
// // System.out.println("null");
// }
else {
System.out.println ("string: "+word+"string length:"+word.length()));
}
}
}
© 2024 OneMinuteCode. All rights reserved.