Pages

Friday, 19 August 2016

Chapter 5 Exercise 43, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*5.43 (Math: combinations) Write a program that displays all possible combinations for picking two numbers from integers 1 to 7. Also display the total number of all combinations.

1 2
1 3
...
...

The total number of all combinations is 21

public class ProgrammingEx5_43 {
 
 public static void main(String[] args) {
 
  int count = 0;
  String s = "";
 
  for (int i = 1; i <= 7; i++) {
   for (int j = 1; j <= 7; j++) {
 
    if (j != i && !s.contains(j + " " + i)) {
     count++;
     s = s + "\n" + i + " " + j;
    }
 
   }
 
  }
  System.out.println(s);
 
  System.out.println("The total number of all combinations is " + count);
 
 }
}

No comments:

Post a Comment