該程式的這一點是將用戶名的字符長度限制為 20 個字符。它是當前僅包含 Main 方法的較大程式的一部分。為了清理和澄清我的代碼,我想將各種功能分成不同的方法。
目前,我正在嘗試設定類變數,以便它們可以在多種方法中使用。這是我到目前為止:
public class Program
{
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void main(String[] args) {
domainCharLimit();
}
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);
}
}
我曾嘗試將一種或兩種方法設定為靜態,但這并沒有解決問題。在這種狀態下,運行時,程式不會回傳錯誤而是給出“無輸出”
uj5u.com熱心網友回復:
Main 方法必須是靜態的!它是你程式的入口,它的簽名必須是這樣的。
為了在其中呼叫非靜態方法,您需要實體化一個物件并在該物件上呼叫它。在你的情況下類似
public static void main(String[] args) {
Program p = new Program();
p.domainCharLimit();
}
uj5u.com熱心網友回復:
第一: Main 方法應該始終是static。
第二:因為你是domainChatLimit()從Main(static)比它也應該是靜態的呼叫
第三:因為您在靜態方法中使用了firstName,lastName屬性,domainChatLimit()那么它們也應該是靜態的
第四: 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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374136.html
上一篇:如何放置空格介紹陣列
下一篇:巧妙地替換字串
