Generating truth tables in Java

后端 未结 7 562
悲哀的现实
悲哀的现实 2021-01-02 16:42

I\'m trying to print some truth tables as part of a school assignment. How can I generate a dynamic size truth table in Java?

So that printTruthTable(1)

7条回答
  •  灰色年华
    2021-01-02 16:59

    here's my take on your problem, all written nice and tight in a small class, just copy/paste

    notice how I used modulo2 (the % sign) to get 0's and 1's from the loop indices

    public class TruthTable {
        private static void printTruthTable(int n) {
            int rows = (int) Math.pow(2,n);
    
            for (int i=0; i=0; j--) {
                    System.out.print((i/(int) Math.pow(2, j))%2 + " ");
                }
                System.out.println();
            }
        }
        public static void main(String[] args) {
            printTruthTable(3); //enter any natural int
        }
    }
    

提交回复
热议问题