对于有2个变量的循环?

时间:2017-01-12 02:36:56

标签: java loops variables for-loop

for (int xGreenBottles = 11, xyGreenBottles = 10; xGreenBottles > 0; xGreenBottles --, xyGreenBottles > 0, xyGreenBottles--)

   if (xGreenBottles == 0 && xyGreenBottles == 0)
   {

    System.out.println(xGreenBottles + " green bottles standing on the wall, " + xGreenBottles + "  green bottles standing on the wall, And if 1 green bottle should accidently fall, there'll be " + xyGreenBottles + " green bottles standing on the wall.");
     }

       else {
       System.out.println("There’ll be no green bottles standing on the wall.");
       }

尝试了十亿种不同的东西,但到目前为止还没有任何工作。如果它没有任何连贯的地方,可能是因为我在过去的4个小时里一直试图这样做而且我的大脑都在炒。很抱歉,如果长的system.out.println难以阅读。

此外 - 它需要使用2个变量。

修改

好的抱歉,我没有说清楚 - 我不确定如何制作' for'有两个变量,因为它不断给我一个错误。大部分时间都给了我一个表达方式。并且想知道如何解决它。

4 个答案:

答案 0 :(得分:0)

for 循环包含由 ; 分隔的3部分:

  • 初始化:初始化循环变量的地方
  • 循环限制(这应该是输出为布尔值的条件)
  • 每次迭代时更新计数器
for(
       int xGreenBottles = 11, xyGreenBottles = 10; 
       (xGreenBottles > 0 && xyGreenBottles > 0); 
       xGreenBottles --, xyGreenBottles--
    )
 {
            }

答案 1 :(得分:0)

您需要将for循环语句替换为:

for ( int xGreenBottles = 11, xyGreenBottles = 10; xGreenBottles > 0 && xyGreenBottles > 0 ; xGreenBottles--, xyGreenBottles-- )

另请注意,如果我正确读取,那么“if”语句永远不会评估为true,因为评估for循环的顺序如下:

  1. 初始化变量(在第一个之前;)
  2. 检查条件(两者之间;;),如果失败则退出循环
  3. 执行代码块
  4. 增量变量(循环的最右边部分,两者之后;;)
  5. 从#2
  6. 重复

    如果两个变量中的任何一个变为零,则循环将在不执行块的情况下中断。

    老实说,我并不完全清楚你用这个代码想要实现的目标,也许提供一些“伪代码”可以帮助我们更好地帮助你...如果有更多的东西,请乐意添加我的答案具体你在寻找!

    希望这有帮助!

答案 2 :(得分:0)

您还没有使用正确的格式。

分号假设根据功能分离for循环,你不能将它们混合起来。

在第一个分号之前,您初始化变量:

int a = 0, b = 0;

在第二个分号之前设置条件(任何返回true或false的表达式):

a < 10 && b < 10;

在最后一节中,您操纵变量:

a++, b++

并且它们将是:

for (int a = 0, b = 0; a < 10 && b < 10; a++, b++)

这只是一个格式化示例,通过它您可以轻松解决问题。

答案 3 :(得分:0)

试试这个。

for (int xGreenBottles = 11, xyGreenBottles = 10; xGreenBottles > 0 && xyGreenBottles > 0; xGreenBottles--, xyGreenBottles--)
{
  if (xGreenBottles == 0 && xyGreenBottles == 0)
  {
    System.out.println(xGreenBottles + " green bottles standing on the wall, " + xGreenBottles + "  green bottles standing on the wall, And if 1 green bottle should accidently fall, there'll be " + xyGreenBottles + " green bottles standing on the wall.");
  }
  else 
  {
    System.out.println("There'll be no green bottles standing on the wall.");
  }
}

我相信你的意思

if (xGreenBottles != 0 && xyGreenBottles != 0)

我发现了几个与此类似的问题,您可能会考虑检查它们并评估给出的答案,以便更好地理解Java for循环语法。 (Java for loop multiple variables

相关问题