第一: Main Method 应该始终是static。
第二:因为你是从Main(static)调用domainChatLimit(),所以它也应该是静态的
第三:因为你在静态方法domainChatLimit()中使用了firstName、lastName属性,那么它们也应该是静态的
第四个:Scanner 也应该是静态的,因为您使用它来获取firstName、lastName,它们都是静态的。
注意:无需定义此类的新实例即可调用内部方法
解决方案应该如下(测试成功):
import java.util.Scanner;
public class Program{
// variables below should be defined as static because they are used in static method
static Scanner read = new Scanner(System.in);
static String firstName = read.nextLine();
static String lastName = read.nextLine();
// Main method is static
public static void main(String[] args) {
//There is no need to define a new instance of this class to call an internal method
domainCharLimit();
}
// calling from main static method so it should be static
public static void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
如果您想为该功能创建一个通用实用程序,您可以执行以下逻辑:
PogramUtil.java
import java.util.Scanner;
public class ProgramUtil {
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
现在你可以这样调用了:
Program.java
public class Program{
// Main method is static
public static void main(String[] args) {
ProgramUtil programUtil = new ProgramUtil();
programUtil.domainCharLimit();
}
}