【发布时间】:2014-08-07 07:56:22
【问题描述】:
我不知道为什么 split 命令对我不起作用,而 sc.nextLine();命令也没有正确读取我的输入,程序正在输出这些:
Menu:
1 - Sign up on service.
这是我的键盘输入
1
程序输出:
Input a single line separated by COMMA and NO SPACES, the software will validade your entry.
1 - Your First Name, 2 - Your Second Name, 3 - Your Age, 4 - Your Gender
(F or M in UPPER CASE) 5 - Your Email, 6 - Your Password:
我的第二个输入:
Vanessa,Jhonson,25, M,aaa@aol.com,111222
现在是我输入后的输出。这是用于打印字符串数组 k[] 的 for 循环的输出,与应有的不接近,不知道为什么。
[Ljava.lang.String;@55f96302
Wrong input pattern, try again. //this is the output if the string s doesn't match the regex
Menu: //Program looping (expected)
1 - Sign up on service.
下面的代码是我的源代码,它有这个主方法和另一个类的另一个方法,在这个之后你就可以了。
package view;
import java.util.Scanner;
import control.RegistrationController;
public class ClientFacade {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
boolean exit = false;
int option = 0;
RegistrationController rc = new RegistrationController();
while(exit == false){
System.out.println("Menu:");
System.out.println("1 - Sign up on service.");
option = sc.nextInt(); //ERROR AT THIS LINE
switch(option){
case 0:{
exit = true;
break;
}
case 1:{
rc.userSignUp();
break;
}
default:{
System.out.println("Invalid option.");
break;
}
}
}
sc.close();
}
}
下面的代码是这个程序的一个方法。 包控制;
import java.util.Scanner;
import java.util.regex.Pattern;
import view.ClientFacade;
import model.Person;
import model.Server;
public class RegistrationController {
public void userSignUp(){
Scanner sc = new Scanner(System.in);
User usr = new User();
RegistrationController rc = new RegistrationController();
String regex = "$(\\w)+(\\,)(\\w)+(\\,)(\\d){2,3}(\\,)[F,M](\\,)(\\w)+(@)(\\w)+(.)(\\w)+((.)(\\w)+)?(,)(\\w)+^";
System.out.println("Input a single line separated by COMMA and NO SPACES, "
+ "the software will validade your entry.\n"
+ "1 - Your First Name, 2 - Your Second Name, "
+ "3 - Your Age, 4 - Your Gender \n(F or M in UPPER CASE) "
+ "5 - Your Email, 6 - Your Password:\n");
String s = sc.nextLine(); //BUG, NOT ABLE TO READ A PROPER STRING
s = s.trim();
String [] k = s.split("(\\,)"); //THIS IS ABSOLUTELY NOT WORKING FOR NO REASON
System.out.println(s); //DEBUGGING LINE
for (int i = 0; i < k.length; i++) { //DEBUGGING BLOCK
String string = k[i];
System.out.println(k);
}
if (Pattern.matches(regex, s)){
usr.setAdmLevel(0);
usr.setName(k[0]+" "+k[1]);
usr.setAge(Integer.parseInt(k[2]));
usr.setGender(k[3]);
usr.setEmail(k[4]);
usr.setPassword(k[5]);
if (rc.registerUser(usr) != 0){
System.out.println("Your are signed up! Your ID: "+usr.getId());
}else {
System.out.println("A problem ocurred, not registered.");
}
}else{
System.out.println("Wrong input pattern, try again.");
}
}
}
【问题讨论】:
-
不需要
\\` ins.split("(\\,)");` -
System.out.println(k);应该是System.out.println(k[i])。您在数组上调用toString()- 这绝不是一个好主意... -
根据您的输入,您的正则表达式模式也不正确
-
您的输入“, M”中还有一个空格,它不按照您自己的说明操作。
-
这一行:s = s.trim();应该消除空格@user2696372,但没有发生
标签: java regex string-split