I’m trying to split a string by a backslash but I’m having problems. I’m sure I have the expression right can someone read what I’ve done and tell me my problem?
package taskstodo;
public class Task {
StringBuilder name;
StringBuilder note;
StringBuilder date;
void setName(String name) {
this.name = new StringBuilder(name);
}
void setNote(String note) {
this.note = new StringBuilder(note);
}
boolean dateIsValid() {
String dateStr = date.toString();
String[] numbers = (dateStr.split("[\\\\]"));
for(String num : numbers) {
System.out.println(num);
if ((num.length()) != 2) {
return false;
}
return true;
}
return true;
}
void setDate(String date) {
this.date = new StringBuilder(date);
}
}
package taskstodo;
public class TasksToDo {
public static void main(String[] args) {
Task myTask = new Task();
myTask.setDate("02/03/20");
System.out.println(myTask.dateIsValid());
Task myTask2 = new Task();
myTask2.setDate("23/45/6001");
System.out.println(myTask2.dateIsValid());
}
}
The TasksToDo class tests the Task class.
It should return:
02
03
20
true
23
45
6001
false
But it returns:
02/03/20
false
23/45/6001
false
You say you want to split by backslash
\but you’re passing in forward slash/to your test case. How can you expect it to work?!Try this