简体   繁体   English

Java-将此方法转换为for和while循环

[英]Java - converting this method to a for and while loop

This is a question from a past exam paper. 这是过去的试卷中的一个问题。 I am not too sure how to convert the extract method to a while and for loop. 我不太确定如何将extract方法转换为while和for循环。

I have attempted this question: the extract1 and extract2 methods but i know they are incorrect. 我已经尝试了这个问题:在extract1extract2方法,但我知道他们是不正确的。 The original method may not be useful but the exam requires you to show how to write methods differently. 原始方法可能没有用,但是考试要求您展示如何以不同的方式编写方法。 I wanted to know how they could be done for future reference. 我想知道如何做以备将来参考。

String extractedThis = "";

public String extract(String text){
    if(text.length()==0){
        return extractedThis;
    } else {
        return extractedThis = text.charAt(0) + extract(text.substring(1));
    }
}

public String extract1(String text) {

    while (text != null) {
        extractedThis = text.charAt(0) + text.substring(1);
    }
    return extractedThis;
}

public String extract2(String text) {

    for (int i = 0; i < text.length(); i++) {

        extractedThis = text.substring(i);
    }

    return extractedThis;

}
public String extractWhileLoop(String text) {
    extractedThis = "";

    while(text.length() > 0) {
        extractedThis += text.charAt(0);
        text = text.substring(1);
    }
    return extractedThis;
}

public String extractForLoop(String text) {
    extractedThis = "";
    for (int i = 0; i < text.length(); i++) {

        extractedThis += text.charAt(i);
    }

    return extractedThis;
}

However, I don't see what exactly your trying to achieve with these methods as the return their input, and could be done much easier 但是,我看不到您尝试使用这些方法确切实现什么作为返回它们的输入,并且可以更轻松地完成

This function juste return the received string followed by the last character of the string (ie: 'abcd' => 'abcdd') in I read it correctly. 此函数只是正确地返回接收到的字符串,然后是字符串的最后一个字符(即:'abcd'=>'abcdd')。 It plays with a global variable in recursive calls, it's fun, but something to avoid at any cost :) 它在递归调用中使用全局变量,这很有趣,但是要不惜一切代价避免:)

public String extract(String text){
  String lastChar = '';
  extractedThis = text;
  while(text.length() > 0) {
    lastChar = text.charAt(0);
    text = text.substring(1);
  }

  return extractedThis = extractedThis + lastChar;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM