忽略具有相似值的事物

时间:2013-10-22 18:36:31

标签: java for-loop

import java.util.Scanner;

public class NoneAreSimilar {

    public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
        System.out.println("Enter your value: " ); 
        int value = in.nextInt();

        if(value < 1) { 
            System.out.println("Wrong input");
            System.exit(0);
        }
        if (value == 1 || value == 2 || value == 3) {
            System.out.println("There are no ways to represent "
                + value + " as a sum of 4 terms");
            System.exit(0);
        }

        if (value == 4) {
            System.out.println("1 + 1 + 1 = 4");
            System.out.println("There is 1 way to represent "
                + value + " as a sum of 4 terms");
            System.exit(0);
        }

           int count = 0;

           for (int a1 = 1; a1 <= value; a1++) {
               for (int b2 = 1; b2 <= value; b2++) {
                   for (int c3 = 1; c3 <= value; c3++) {
                       for (int d4 = 2; d4 <= value; d4++) {
               int added = a1 + b2 + c3 + d4; 

               if (added == value) {
                   count++; 
                   System.out.println( a1 + "+" + b2 + "+" + c3 + "+" + d4 + "=" + value);

               }

                       }
                   }
                }
            }
         System.out.println("There are only " + count + 
          " ways to represent the number " + value + " as a sum of 4 terms");
    }
}

我的代码目前有效,但我无法忽略类似的序列。换句话说,当我输入8时,我希望它打印1 + 1 + 2 + 4并忽略重新排列此(1+2+4+1, 1+2+1+4, etc)的其他方法。我已经尝试了if语句,但它们在7之后停止工作,我尝试以不同的值启动,但在8之后,它停止工作。我觉得我的for循环中的值需要在其他地方启动,但我不知道在哪里。有人可以帮我确定需要进行调整的地方吗?

0 个答案:

没有答案