3 回答
TA贡献1846条经验 获得超7个赞
尝试用这个:
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
int oddNumbers = 0;
int evenNumbers = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
if(evenOdd(randomInteger)) evenNumbers++;
else oddNumbers++;
}
System.out.printf("Even numbers: %d - Odd numbers: %d", evenNumbers, oddNumbers);
}
public static boolean evenOdd(int x)
{
if ((x % 2) == 0)
{
System.out.println("Even");
return true;
}
else
{
System.out.println("Odd");
return false;
}
}
您原来的方法不起作用,因为每次调用该方法时都会将oddNumbers和变量初始化为 0。evenNumbers
TA贡献1712条经验 获得超3个赞
Java 不是 JavaScript。而且,它不具备C++“函数中的静态变量”的能力。
方法内声明的变量是局部的。每次代码到达方法内的变量定义时都会发生变量初始化,并在退出方法后被销毁。
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
所以你有这样的变体:
1) 在主方法中计算数字并从实用程序方法返回指示器。
1.1) 布尔值
public static boolean isEven(int x){
return (x % 2) == 0;
};
1.2) 枚举
private enum NumberType {
EVEN,
ODD
}
public static NumberType getNumberType (int x) {
if ((x % 2) == 0) {
return NumberType.EVEN;
} else {
return NumberType.ODD;
}
};
2)使变量静态:
public class EvenOdd {
private static int evenNumbersCount = 0;
private static int oddNumbersCount = 0;
public static void main(String[] args) {
// your code
}
public static void countNumberType (int x) {
if ((x % 2) == 0) {
++evenNumbersCount;
} else {
++oddNumbersCount;
}
}
}
3)在一些复杂的情况下,您需要将容器传递给您的方法:
public class EvenOdd {
private static final String EVEN = "even";
private static final String ODD = "odd";
public static void main(String[] args) {
// initialize container
Map<String, Integer> evenOddCounts = new HashMap<>(2, 1);
evenOddCounts.put(EVEN, 0);
evenOddCounts.put(ODD, 0);
Random random = new Random();
int randomInteger = 0;
for (int i = 0; i < 100; i++) {
randomInteger = random.nextInt();
countNumberType(evenOddCounts, randomInteger);
}
System.out.println(evenOddCounts.toString());
}
public static void countNumberType(Map<String, Integer> counts, int x) {
if ((x % 2) == 0) {
counts.compute(EVEN, (numberType, count) -> ++count);
} else {
counts.compute(ODD, (numberType, count) -> ++count);
}
}
}
添加回答
举报