Java - 通过反斜杠(\)分割字符串
我试图用反斜杠分割字符串,但遇到了问题。我确信我的表达是正确的,有人可以阅读我所做的事情并告诉我我的问题吗?
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);
}
}
打包任务;
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());
}
}
TasksToDo 类测试 Task 类。
它应该返回:
02
03
20
true
23
45
6001
false
但它返回:
02/03/20
false
23/45/6001
false
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您说您想用反斜杠
\
分割,但您将正斜杠/
传递给您的测试用例。你怎么能指望它能发挥作用呢?试试这个
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
要检查您的日期,您可以让 Jdk 为您进行解析。
To check your date you can let the Jdk doing the parsing for you .