java - 我的 while 循环中的条件似乎不正确?

标签 java die

尝试编写一个程序, throw 3 次骰子,一旦连续获得 3 个 6,它就会打印出尝试了多少次。代码末尾有问题,|| 之间的差异而&&,好像是相反的,看看...


package javaapplication12;
import java.util.*;

public class JavaApplication12 {
public static void main(String[] args) {
  Random rand = new Random();
  // this should try to cast a die 3 times and keep doing that until we get 3 6s in a row and counter 
  // how many tries it takes to get that.
  int array[] = new int[3]; // creating 3 places for castin our die 3 times in a row
  int counter1 = 0; // creating a counter to track each time we try to cast 3 die ( 3 cast = 1 try)
  do{

      counter1++; 
      System.out.println("try " + counter1); // prints out counter in the beginning of every try.

      for (int counter = 0; counter < array.length; counter++ ){
          array[counter]=(rand.nextInt(6)+1);  // a loop that fills the array with random numbers from 1-6
      }
      for(int x: array)
          {System.out.println(x);} // this is for our own to check if we have 3 6s in a row,
                                   // prints out all the numbers in out array
  }

  //so this is the I'veusing part, i've written 3 scenarios that can be written for the condtion in our
  // do- while loop...

  while (array[0]+array[1]+array[2] != 18); // this works just fine.

  while (array[0] !=6 || array[1] != 6 || array[2] != 6); // imo this should not work but surprisingly it does

  while (array[0] !=6 && array[1] != 6 && array[2] != 6); // this should work, but it doesnt.


  } 
}

最佳答案

我相信您的困惑来自 De Morgan's laws of negation .基本上,当您否定一组条件时,您应该将 && 更改为 ||,反之亦然,当您否定单个条件时。

或者简单地说:

!(A && B) == !A || !B
!(A || B) == !A && !B

在你的情况下,你想这样做:

!(array[0] == 6 && array[1] == 6 && array[2] == 6)

又名。 “虽然第一个是 6,第二个是 6,第三个是 6 是不正确的”

由于上面的规律,为了把!带进去,需要把&&改成||,导致

!(array[0] == 6) || !(array[1] == 6) || !(array[2] == 6)

简化为

array[0] != 6 || array[1] != 6 || array[2] != 6

关于java - 我的 while 循环中的条件似乎不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54806594/

相关文章:

java - 如何清理 thymeleaf 模板的 json 输出?

java - 如何在 NetBeans 中设置 JFrame 的 setDefaultCloseOperation() 值?

java - 父类(super class)和子类都有自己的接口(interface)

Perl:在不死的情况下捕获错误

perl - 如果我的代码中有未经检查的异常,Perl 编译器能告诉我吗?

java - OSGI 上的 Shiro 注释

java - 在浏览器上编译时使用 Web 应用程序时出现 Eclipse 上的 OutOfMemoryError

php - register_shutdown_function() 和 die()

jquery - 停止函数,jQuery

perl - 用于测试 Perl 脚本/模块异常和死亡的单元测试