简体   繁体   English

Java 条件语句混淆

[英]Java conditional statement confusion

Testing out a simple while loop but I'm confused, if bottle is 1 ,name is "bottle" .测试一个简单的 while 循环,但我很困惑,如果bottle1 ,name 是"bottle"

But even when bottle is greater that 1 , it still prints "bottle" and not "bottles"但即使当bottle大于1时,它仍然打印"bottle"而不是"bottles"

public class ex {
  public static void main(String[] arg) {
    int bottle = 0;
    String name = "bottles";
    while (bottle < 100) {
      if (bottle == 1) {
        name = "bottle";
      }
      System.out.println(bottle + " " + name);
      ++bottle;
    }
  }
}

Variable name keeps the value in singular as is never reasigned with the "bottles" value.变量name将值保持为单数,因为永远不会用“瓶子”值重新分配。 Try this:尝试这个:

public static void main(String[] arg) {
  int bottle = 0;
  String name = "bottles";
  while( bottle < 100) {
    name = "bottles"
    if(bottle == 1) {
      name = "bottle";
    }
    System.out.println(bottle + " " + name);
    ++bottle;
  }
}

Once you set name = "bottle";一旦你设置了 name = "bottle"; then name will always be "bottle" unless you change it back.那么 name 将永远是“bottle”,除非你把它改回来。 After the if statement add:在 if 语句之后添加:

else {
    name = "bottles";
}
  if (bottle == 1) {
    name = "bottle";
  }else{
    name = "bottles";
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM