为了账号安全,请及时绑定邮箱和手机立即绑定

调用自己的方法时,旧字符串值会留下

调用自己的方法时,旧字符串值会留下

汪汪一只猫 2023-08-23 10:39:40
当我收到不需要的输入时,我再次调用该方法,但在第二次迭代时,字符串上仍然留有一个字符。为什么它不创建一个全新的字符串并替换旧的值?所以首先我在扫描仪中输入“mmmm”,这会触发 if 语句中的条件并调用createSocial(),然后重新运行循环,然后我输入新的输入 5555。现在这是我没有得到的:当我打印出新的字符串时,它们显示为 5555,但是在循环中打印它们时留下了“m”,为什么?    public class test {    public static String createSocial() {            Scanner sc = new Scanner(System.in);            String social = sc.nextLine();            String digit = social;             System.out.println(social + "     SOCIAL");            System.out.println(digit + "     DIGIT");            if (social.length() != 4) {                System.out.println("You did not type 4 digits, try again");                  createSocial();             }            //check non-integers                    while(digit.length() > 0) {                System.out.println( digit.charAt(0) + "<---");                  if(Character.isDigit( digit.charAt(0) ) == false) {                    System.out.println("You did not type your last 4 digits correctly, try again");                     createSocial();                  }                digit = digit.substring(1);             }               return social;         }}这是我的输出:    enter the last 4 digits of your Social Security number    mmmm    //(This is my first input for the scanner)    mmmm     SOCIAL    mmmm     DIGIT    m<---    You did not type your last 4 digits correctly, try again    5555   //(this is my input for the scanner the second time around)    5555     SOCIAL    5555     DIGIT    5<---    5<---    5<---    5<---    m<---    You did not type your last 4 digits correctly, try again
查看完整描述

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}")) {

基本上意味着:如果用户输入字符串不是四位整数值,则显示“无效输入!” 信息。


查看完整回答
反对 回复 2023-08-23
  • 1 回答
  • 0 关注
  • 114 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信