从给定数字

时间:2017-09-19 00:59:30

标签: java

我需要编写一个Java程序来列出集合{1,2,..,n}的所有子集。程序的输入将是正整数n,输出将是集合{1,2,....,n}的子集列表。

我可以打印出正确的子集,但我总是有一个尾随的逗号{1,2,....,n,},我无法弄清楚如何删除它。任何帮助都很棒!谢谢

import java.util.Scanner;

public class Lab1 {
    public static void main(String[] args)
    {
        //initialize array
        int[] setArray;
        Scanner keyboard = new Scanner(System.in);
        //Gets Set number from user
        System.out.print("Given Positive Number: ");
        String stringChoice = keyboard.nextLine();
        int choice;
        while (true) {
            try {
                //makes sure user's choice is a number within the limits
                choice = Integer.parseInt(stringChoice);
                if (choice >=0) {
                    break;
                }
            } catch (NumberFormatException e) {
                // do nothing.
            }
            System.out.print("Enter valid option: ");
            stringChoice = keyboard.nextLine();
        }


        System.out.println("All Given Subsets: \n");
        //Set's array size to the number that the  user inputed
        setArray = new int[choice];
        //fills array from 1 to the number that the user inputed
        for (int i=choice; i>0; i--){
            setArray[i-1]=i;
        }

        //Calls Print All Subset function
        printAllSubsets(setArray);


        keyboard.close();
    }


        // Print all subsets of given set[]
        static void printAllSubsets(int setArray[]){
            int n = setArray.length;

            for (int i = 0; i < (1<<n); i++){
                System.out.print("{ ");

                // Print current subset
                for (int j = 0; j < n; j++){

                    // (1<<j) is a number with jth bit 1
                    // so when we 'and' them with the
                    // subset number we get which numbers
                    // are present in the subset and which
                    // are not
                    if ((i & (1 << j)) > 0){
                        System.out.print(setArray[j] + " , ");
                    }

                }
                System.out.println("}");

            }
        }

}

1 个答案:

答案 0 :(得分:0)

.endsWith(String regex).substring(int startIndex, int endIndex)是您的朋友。

String str = "Trailing, comma, example,";
        if(str.endsWith(",")){
            str = str.substring(0, str.length()-1);
        }
        System.out.println(str);

或者如果您不想更改字符串的内容......

if (str.endsWith(",")) {
        System.out.println(str.substring(0, str.length() - 1));
    } else {
        System.out.println(str);
    }