gpt4 book ai didi

java - 有没有更 Eloquent 方式来编程这个方法?

转载 作者:行者123 更新时间:2023-12-01 12:21:29 26 4
gpt4 key购买 nike

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”,但是每当我尝试在方法中引用它时,它都不在主方法的范围内。所以我的解决方法是使其成为“公共(public)静态整数”。有更好的方法吗?

最佳答案

由于您的方法返回 int,因此您只需在 main 方法中使用 numI 返回的值分配一个 int 即可

例如:

int result = numI(testString,testCh);

这意味着从类中删除 static int num 声明,并在 numI 方法范围内初始化并返回一个 int

例如(在numI内):

int result = 0;
for(int i = 0;i<test.length();i++){
...
// TODO assign/increment/print "result" instead of former "num"
return result;

关于java - 有没有更 Eloquent 方式来编程这个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26635825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com