【发布时间】:2014-10-29 16:31:28
【问题描述】:
import java.util.Scanner;
public class MethodWalkthrough {
private static int num = 0;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
boolean stringHasI = true;
while(stringHasI){
String testString = kb.next(); //String to test
char testCh = kb.next().charAt(0); //char to determine how many instances it appears in testString
numI(testString,testCh);
if(num==0)
stringHasI = false;
num=0;
}
}
public static int numI(String test, char testChar){
for(int i = 0;i<test.length();i++){
if(test.charAt(i)==testChar)
num++;
}
System.out.println("There are "+num+" "+testChar+"'s in "+test);
return num;
}
}
我想实际利用返回的值“num”,但是每当我尝试在方法中引用它时,它不在主方法的范围内。所以我的解决方法是使其成为“公共静态 int”。有更好的方法吗?
【问题讨论】:
-
你甚至不使用函数
numI的返回值。