Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中用不同的方法打印出非变量int_Java_String_Variables - Fatal编程技术网

在Java中用不同的方法打印出非变量int

在Java中用不同的方法打印出非变量int,java,string,variables,Java,String,Variables,我试图测试查找数组中奇数的方法是否适用于System.out.println()调用。我知道数组本身没有问题,因为我已经使用toString()调用成功地打印了它。以下是我的方法: public static int ODD(int[] oddnumbers) { int countOdds = 0; for(int i = 0; i < oddnumbers.length; i++) { if(oddnumbers[i] % 2 == 1) // chec

我试图测试查找数组中奇数的方法是否适用于
System.out.println()
调用。我知道数组本身没有问题,因为我已经使用toString()调用成功地打印了它。以下是我的方法:

public static int ODD(int[] oddnumbers)
{
    int countOdds = 0;
    for(int i = 0; i < oddnumbers.length; i++)
    {
    if(oddnumbers[i] % 2 == 1) // check if it's odd
          countOdds++;        // keep counting
      }
      return countOdds;

}
}

基本上,我的问题是,如何将
return countloffics
转换成一个变量,然后在
main
方法中的System.out.println()中进行打印

只要做:


System.out.println(“这是该数组中有多少奇数:”+odd(randomThreen))

使用
int countloffics=奇数(随机数)在主方法中


函数中的
countforbits
变量是该函数的局部变量。java函数中定义的变量是局部变量而不是全局变量。

使用临时变量存储返回值并打印该值,或者在print语句中包含方法调用。有关更多信息,请参见。

您只需将
ODD
方法调用的结果分配给变量:

public static void main(String args[])
{
    int result = ODD(randomThirty);  // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
    System.out.println("And here are how many odd numbers there are in that array: " + result);
}
int countOdds = ODD(randomThirty);

您需要将调用
ODD
的返回结果存储在变量中,如下所示:

public static void main(String args[])
{

    int countOdds = ODD(randomThirty);  // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
    System.out.println("And here are how many odd numbers there are in that array: " + countOdds);
}

只需像保存任何其他变量一样保存结果:

public static void main(String args[])
{
    int result = ODD(randomThirty);  // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
    System.out.println("And here are how many odd numbers there are in that array: " + result);
}
int countOdds = ODD(randomThirty);

要获取返回值,必须将参数传递到方法并调用它

    int ans = ODD(randomThirty); 
    System.out.println(ans);

这就是你真正需要做的。您可以在传递参数的同时调用方法,并为返回的答案分配一个变量。

谢谢Saket,这很有意义,我只是输入从ODD方法返回的任何内容。我以后会记住的,谢谢!