假设这个问题与您之前的问题Java String Limit相关,您可能不需要在 setusername() 方法中使用 return 语句。
import java.io.*;
public class UserNameTest {
private static final int USER_NAME_LIMIT=6; // constants should be all UPPERCASE_WITH_UNDERSCORES
private String userName; // variable names should be in camelCase
private String getUserName() {
// normally you write a getter method to obtain value
return userName;
}
private void setUserName(String u) {
// setter method would not require a return statement,
// if all you trying to do is to validate and set the new value.
if (u.length() > USER_NAME_LIMIT) { // validate length of new value
// good practice to be descriptive when giving error messages
System.out.println("Given user name [" + u + "] is longer than valid limit [" + USER_NAME_LIMIT + "]");
} else {
this.userName = u;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputString = br.readLine();
UserNameTest q1 = new UserNameTest();
q1.setUserName(inputString); // set user name retrieved through input
System.out.println("New user name: " + q1.getUserName()); // get user name for other operations
// if setUserName() above rejected the input value due to length exceeding, here you will see 'null'
// as we have not set user name to anything beforehand
}
}
阅读并了解编码标准以及http://geosoft.no/development/javastyle.html