1 回答

TA貢獻1946條經(jīng)驗 獲得超3個贊
您看到m 的原因如下:
5<---
5<---
5<---
5<---
m<---
僅僅是因為您在開始遞歸調(diào)用之前沒有清除社交字符串變量。實際上,當(dāng)進行此遞歸調(diào)用時,您應(yīng)該這樣做:
social = createSocial();
這樣,您就可以保證Social將始終保留該遞歸調(diào)用的真實值,而不是先前遞歸調(diào)用的值。如果您不從createSocial()方法獲取返回值,您將永遠不會獲得新結(jié)果,因為社交變量的范圍對于方法本身而言是本地的。您需要接受返回值,就像第一次初始調(diào)用createSocial()方法時所做的那樣。
但這還不是全部,您還需要在每次遞歸調(diào)用( )之后更新數(shù)字digit = social;變量內(nèi)容。在我看來,這比必要的更復(fù)雜。我理解為什么您添加了數(shù)字變量,但是如果您仔細查看代碼,您可以通過繼續(xù)利用社交變量來進行數(shù)字細分來完成同樣的事情。您只需在該方法返回的變量中進行數(shù)值細分之前,將原始值保存在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;
}
使用您發(fā)布的示例參數(shù)(mmmmm 和 5555),您可以使用上面的代碼,如下所示:
System.out.println(createSocial());
輸入mmmmm和5555后,控制臺的輸出結(jié)果將如下所示:
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 <---?因為單次遞歸調(diào)用。標(biāo)記為 5 的方法調(diào)用:1是對createSocial () 方法的初始調(diào)用。任何超過 1 的方法調(diào)用都是遞歸調(diào)用。每次調(diào)用時5 <---都會列出四個。
這一切都可以以更簡單的方式完成,并且不需要遞歸來執(zhí)行此任務(wù),可以使用循環(huán)來代替,例如:
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()方法和一個小的正則表達式來檢查數(shù)據(jù)輸入的有效性,消除了對大量代碼的需要,并使內(nèi)容更容易閱讀。上面兩個代碼示例中IF語句條件的matches()方法中使用的正則表達式 (RegEx)
if (!social.matches("\\d{4}")) {
基本上意味著:如果用戶輸入字符串不是四位整數(shù)值,則顯示“無效輸入!” 信息。
添加回答
舉報