How to split a string at a space?

ساخت وبلاگ

Vote count: 0

Whenever I try to create a new student, my code just doesn't work, regardless of my entry. This method should split a string at a space, and if there are 0 spaces, or more than two, then an error message should be printed, and the value of name shouldn't change. If there is one space present, then the substring before the space becomes firstName and the substring after becomes lastName. If there are two spaces, then the substring before the first space becomes firstName, the one after the first space becomes middleName, and the one after the second space becomes lastName. I'm not sure what I am doing wrong here since my code compiles, but whenever I try to call this method, no student is created.

public void setName(String newName)
{ String[] nameInput = newName.split(" "); int count = 0; int i = 0; for (String userName : nameInput) { while(i < newName.length()) if(newName.charAt(i) == ' ') { count++; } if (count == 0) { System.out.println("Error, please enter at least two names."); newName = null; } else if(count==1) { firstName = nameInput[1]; middleName = ""; lastName = nameInput[2]; newName = firstName + " " + lastName; } else if(count == 2) { firstName = nameInput[1]; middleName = nameInput[2]; lastName = nameInput[3]; newName = firstName + middleName + lastName; } else { System.out.println("Error! You can only enter up to three names."); } }
}
asked 54 secs ago

- - , .

back soft...
ما را در سایت back soft دنبال می کنید

برچسب : نویسنده : استخدام کار backsoft بازدید : 375 تاريخ : جمعه 30 بهمن 1394 ساعت: 12:36