1 回答

TA貢獻1946條經驗 獲得超3個贊
您看到m 的原因如下:
5<---
5<---
5<---
5<---
m<---
僅僅是因為您在開始遞歸調用之前沒有清除社交字符串變量。實際上,當進行此遞歸調用時,您應該這樣做:
social = createSocial();
這樣,您就可以保證Social將始終保留該遞歸調用的真實值,而不是先前遞歸調用的值。如果您不從createSocial()方法獲取返回值,您將永遠不會獲得新結果,因為社交變量的范圍對于方法本身而言是本地的。您需要接受返回值,就像第一次初始調用createSocial()方法時所做的那樣。
但這還不是全部,您還需要在每次遞歸調用( )之后更新數字digit = social;變量內容。在我看來,這比必要的更復雜。我理解為什么您添加了數字變量,但是如果您仔細查看代碼,您可以通過繼續利用社交變量來進行數字細分來完成同樣的事情。您只需在該方法返回的變量中進行數值細分之前,將原始值保存在social中,例如:
private static int methodCalls = 0; // Class Global Member Variable
public static String createSocial() {
methodCalls++;
Scanner sc = new Scanner(System.in);
String social = sc.nextLine();
System.out.println(social + " SOCIAL");
if (social.length() != 4) {
System.out.println("You did not type 4 digits, try again");
social = createSocial();
}
// returnResult will eventually will hold the
// valid result to return.
String returnResult = social;
//check non-integers
while (social.length() > 0) {
System.out.println(social.charAt(0) + " <--- Method call: " + methodCalls);
if (Character.isDigit(social.charAt(0)) == false) {
System.out.println("You did not type your last 4 digits correctly, try again");
social = createSocial();
}
social = social.substring(1);
}
methodCalls--;
return returnResult;
}
使用您發布的示例參數(mmmmm 和 5555),您可以使用上面的代碼,如下所示:
System.out.println(createSocial());
輸入mmmmm和5555后,控制臺的輸出結果將如下所示:
mmmmm
mmmmm SOCIAL
You did not type 4 digits, try again
5555
5555 SOCIAL
5 <--- Method call: 2
5 <--- Method call: 2
5 <--- Method call: 2
5 <--- Method call: 2
5 <--- Method call: 1
5 <--- Method call: 1
5 <--- Method call: 1
5 <--- Method call: 1
5555
為什么都是5 <---?因為單次遞歸調用。標記為 5 的方法調用:1是對createSocial () 方法的初始調用。任何超過 1 的方法調用都是遞歸調用。每次調用時5 <---都會列出四個。
這一切都可以以更簡單的方式完成,并且不需要遞歸來執行此任務,可以使用循環來代替,例如:
public static String createSocial() {
String ls = System.lineSeparator();
Scanner sc = new Scanner(System.in);
String social = "";
while (social.equals("")) {
System.out.print("Please enter the last four digits of " + ls
+ "your Social Security Number: --> ");
social = sc.nextLine();
if (!social.matches("\\d{4}")) {
System.err.println("Invalid Entry! Please Try Again..." + ls);
social = "";
}
}
return social;
}
但如果需要遞歸,那么你可以這樣做:
public static String createSocial() {
String ls = System.lineSeparator();
Scanner sc = new Scanner(System.in);
String social = "";
System.out.print("Please enter the last four digits of " + ls
+ "your Social Security Number: --> ");
social = sc.nextLine();
if (!social.matches("\\d{4}")) {
System.err.println("Invalid Entry! Please Try Again..." + ls);
social = createSocial();
}
return social;
}
使用 Java 的String#matches()方法和一個小的正則表達式來檢查數據輸入的有效性,消除了對大量代碼的需要,并使內容更容易閱讀。上面兩個代碼示例中IF語句條件的matches()方法中使用的正則表達式 (RegEx)
if (!social.matches("\\d{4}")) {
基本上意味著:如果用戶輸入字符串不是四位整數值,則顯示“無效輸入!” 信息。
添加回答
舉報