[英]Returning a single string from a method with multiple loops in java
I am a newbie in Java and having difficulty in returning a single string from a method that has multiple for loops, each loop iterating 25 times and returning a pass/fail for each iteration. 我是Java的新手,很难从具有多个for循环的方法返回单个字符串,每个循环迭代25次,并为每次迭代返回通过/失败。 I'm trying to figure out what to do so if any of the for loops return a "fail" the over all method returns a fail, otherwise it just returns a "pass"? 我试图弄清楚如果任何for循环返回“失败”,则整个方法返回失败,否则,它只是返回“通过”? Following is a generic code I have. 以下是我的通用代码。
public String myMethod (String string, String string2) {
for (int i = 0; i < 25 ; i++){
B = string1 + i + string 2;
if (B.equals("something"){
return "Pass";
}else{
return "Fail";
}
for (int j = 0; j < 25 ; j++) {
C = string3 + i + string 4;
if (C.equals("something")){
return "Pass";
}else{
return "Fail";
}
for (int k = 0 ; k < 25 ; k++) {
D = string4 + i + string 5;
if (D.equals("something")){
return "Pass";
}else{
return "Fail";
}
}
if any of the for loops return a "fail" the over all method returns a fail 如果任何for循环返回“失败”,则全部方法返回失败
The for
-loops do not return a value. for
循环不返回值。 Those return
statements within the loops are returning a value for the entire method. 循环中的那些return
语句将返回整个方法的值。 This shouldn't really be a problem, however, as you can do something along the lines of 但是,这实际上不是问题,因为您可以按照以下步骤进行操作
public String myMethod(String string1, String string2) {
for (int i = 0; i < 25; i++) {
B = string1 + i + string2;
if (!B.equals("something"))
return "Fail"; // we know the entire method should
// return "Fail" here
}
// other loops, same format
return "Pass"; // we know nothing returned "Fail" at this point,
// so we return "Pass"
}
Note that this short-circuit-esque approach will be more efficient than maintaining a variable with the result of the method, as time will not be wasted continuing the method once we know what its return value should be. 请注意,这种类似短路的方法将比通过方法的结果保持变量更有效,因为一旦知道返回值应该是什么,继续进行该方法就不会浪费时间。
Just use one variable with default as PASS . 只需使用一个默认值为PASS的变量即可。 Set the value to FAIL when it fails and return in the end as below: 失败时将值设置为FAIL ,并最终返回如下:
public String myMethod (String string, String string2) {
String result = "Pass";
for (int i = 0; i < 25 ; i++){
B = string1 + i + string2;
if (!B.equals("something"){
result = "Fail";
}
}
for (int j = 0; j < 25 ; j++) {
C = string3 + i + string4;
if (!C.equals("something")){
result = "Fail";
}
}
for (int k = 0 ; k < 25 ; k++) {
D = string4 + i + string5;
if (!D.equals("something")){
result = "Fail";
}
}
//return the final result, which is fail if it fails one ore more times
return result;
}
Side Note: Not sure of the declaration of String B, C, D String1..... etc. Take care of them if not already done. 旁注:不确定字符串B,C,D的声明String1 .....等。请注意它们(如果尚未完成)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.