Java—将此方法转换为for和while循环
这是一道过去的试卷上的题。我不太确定如何将Java—将此方法转换为for和while循环,java,for-loop,while-loop,Java,For Loop,While Loop,这是一道过去的试卷上的题。我不太确定如何将extract方法转换为while和for循环 我尝试过这个问题:extract1和extract2方法,但我知道它们是不正确的。原始方法可能没有用处,但考试要求您展示如何以不同的方式编写方法。我想知道如何做,以备将来参考 String extractedThis = ""; public String extract(String text){ if(text.length()==0){ return extractedThi
extract
方法转换为while和for循环
我尝试过这个问题:extract1
和extract2
方法,但我知道它们是不正确的。原始方法可能没有用处,但考试要求您展示如何以不同的方式编写方法。我想知道如何做,以备将来参考
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;
}
String extractedThis=“”;
公共字符串提取(字符串文本){
如果(text.length()==0){
回程提取;
}否则{
return extractedThis=text.charAt(0)+extract(text.substring(1));
}
}
公共字符串提取器1(字符串文本){
while(text!=null){
extractedThis=text.charAt(0)+text.substring(1);
}
回程提取;
}
公共字符串提取器2(字符串文本){
对于(int i=0;i
公共字符串提取WhileLoop(字符串文本){
提取此项=”;
while(text.length()>0){
extractedThis+=text.charAt(0);
text=text.子字符串(1);
}
回程提取;
}
公共字符串extractForLoop(字符串文本){
提取此项=”;
对于(int i=0;i
但是,我看不出这些方法在返回其输入时究竟要实现什么,而且可以更轻松地完成此功能此函数只需返回接收到的字符串,然后返回该字符串的最后一个字符(即:“abcd”=>“abcdd”),在我正确读取后即可。 它在递归调用中使用全局变量,这很有趣,但无论如何都要避免:)
你测试过你的方法吗?
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;
}
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;
}