如何将String转换为数字并对其进行排序?

时间:2015-01-30 07:57:13

标签: java sorting

有人可以告诉我解决问题的方法。要求是显示一个菜单,其中包含选择冒泡排序,插入排序。允许用户输入无限数量,并根据他们的选择对这些数字进行排序。我搞不清楚了。这是我一直在研究的代码。我很困惑如何让用户输入一个String并将它们拆分为int并对它们进行排序,以及如何将结果输出到toString()。

public class IntegerArraySorting{
    private int[] integerArray;
    int sortingMethod;

    public IntegerArraySorting(String listNumber, int sortingMethod) {
        //StringTokenizer strToken = new StringTokenizer(listNumber, " ");
        for(int i = 0; i < listNumber.length(); i++){
            integerArray[i] = Integer.parseInt(listNumber);
        }
        switch(sortingMethod){
        case 1: 
            System.out.println("Sorting method: BUBBLE SORT");
            //Integer.parseInt(listNumber).bubbleSort();
            break;
            default:
                System.out.println("Wrong Input");
        }

    }

    public void insertionSort() {
        for (int i = 1; i < integerArray.length; i++) {
            int j = i;
            int B = integerArray[i];
            while ((j > 0) && (integerArray[j - 1] > B)) {
                integerArray[j] = integerArray[j - 1];
                j--;
            }
            integerArray[j] = B;
        }
    }// where array is an array with size = n

    public void bubbleSort() {
        int n = integerArray.length;
        for (int pass = 1; pass < n; pass++) { // count how many times
            // This neintegerArrayt loop becomes shorter and shorter
            for (int i = 0; i < n - pass; i++) {
                if (integerArray[i] > integerArray[i + 1]) {
                    // exchange elements
                    int temp = integerArray[i];
                    integerArray[i] = integerArray[i + 1];
                    integerArray[i + 1] = temp;
                }
            }
        }
    }// where integerArray is an array with size = n

    public void selectionSort() {
        for (int i = 0; i < integerArray.length - 1; i++) {
            for (int j = i + 1; j < integerArray.length; j++) {
                if (integerArray[i] > integerArray[j]) {
                    // ...Exchange elements
                    int temp = integerArray[i];
                    integerArray[i] = integerArray[j];
                    integerArray[j] = temp;
                }
            }
        }
    }// where integerArray is an array with size = n

    public String toString(){
        String str = "";
        for(int i = 0; i < integerArray.length; i++){
         str = str + Arrays.toString(integerArray);
        }
        return str;
    }

}

4 个答案:

答案 0 :(得分:1)

  

我很困惑如何让用户输入一个String并将它们拆分为int并对它们进行排序,

有许多方法可以从用户输入内容并使用它。最简单的方法是使用输入流并将其传递给扫描程序实例,如下所示

Scanner inputScanner = new Scanner(System.in);
// since your sorting method is an int
int userChoice = inputScanner.nextInt();

// now just pass this to the method and you have your input problem solved, 
//Yes you will have to make an object of your class
classObject.IntegerArraySorting(yourList, userChoice)
  

以及如何将结果输出到toString()。

//just call the method and it will display your toString() implementation

classObject.toString()

答案 1 :(得分:0)

我已经为您简化了代码,并在必要时添加了说明,请查看,

有两个类,IntegerArraySortingMain

我已经为int中的IntegerArraySorting数组编写了排序算法和getter / setter的代码,而我已经从Main类创建了此类的实例。我还删除了构造函数,并为输入创建了一个名为selectAndStartSorting的新方法,以便选择排序算法。

回答你的问题,

  

我很困惑如何让用户输入一个String并将它们拆分为int

您可以使用split()类的String方法根据任何正则表达式表达式拆分字符串,然后使用int将结果字符串数组解析为Integer.parseInt

  

以及如何将结果输出到toString()。

String数组解析为int数组并进行排序后,您可以使用Arrays.toString方法将已排序的int数组转换回StringArrays.toString(int [])

请参阅以下代码

这里是IntegerArraySorting类,

import java.util.Arrays;

public class IntegerArraySorting{

    private int[] integerArray;

    // Getters/setters for array,
    public int[] getArray(){
        return integerArray;
    }

    public void setArray(int [] inputArray){
        integerArray = inputArray;
    }


    // Method to select sorting algorithm
    public void selectAndStartSorting(int sortingMethod) {

        switch(sortingMethod){
        case 1: 
            System.out.println("Sorting method: BUBBLE SORT");
            bubbleSort();
            System.out.println("DONE");
            break;
        case 2:
            System.out.println("Sorting method: INSERTION SORT");
            insertionSort();
            System.out.println("DONE");
            break;
        case 3:
            System.out.println("Sorting method: SELECTION SORT");
            selectionSort();
            System.out.println("DONE");
            break;
        default:
           System.out.println("Wrong Input");
        }
    }

    public void insertionSort() {
        for (int i = 1; i < integerArray.length; i++) {
            int j = i;
            int B = integerArray[i];
            while ((j > 0) && (integerArray[j - 1] > B)) {
                integerArray[j] = integerArray[j - 1];
                j--;
            }
            integerArray[j] = B;
        }
    }


    public void bubbleSort() {
        int n = integerArray.length;
        for (int pass = 1; pass < n; pass++) { 
            for (int i = 0; i < n - pass; i++) {
                if (integerArray[i] > integerArray[i + 1]) {
                    // exchange elements
                    int temp = integerArray[i];
                    integerArray[i] = integerArray[i + 1];
                    integerArray[i + 1] = temp;
                }
            }
        }
    }


    public void selectionSort() {
        for (int i = 0; i < integerArray.length - 1; i++) {
            for (int j = i + 1; j < integerArray.length; j++) {
                if (integerArray[i] > integerArray[j]) {
                    // ...Exchange elements
                    int temp = integerArray[i];
                    integerArray[i] = integerArray[j];
                    integerArray[j] = temp;
                }
            }
        }
    }

    // Converting sorted int array into String
    public String toString(int [] array){
        return Arrays.toString(array);
    }
}

这里是Main类,

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter Numbers in this format 2,4,51,42,4?");

        // String input must be in this format 1,2,3,5,3,7,9 i.e sperated by commas,
        String str = input.next();

        // Split the input string on every "," and save the resulting array as a String. 
        String[] strArray = str.split(",");

        // Create new int array to later hold the numbers
        int[] numbers = new int[strArray.length];


        for (int i = 0; i < numbers.length; i++) {
            // Convert each number from String array into int and put it in numbers array
            numbers[i] = Integer.parseInt(strArray[i]);
        }

        // Create instance of IntegerArraySorting class,
        IntegerArraySorting first = new IntegerArraySorting();

        // set the Array in IntegerArraySorting (integerArray) to our integer array (numbers) 
        first.setArray(numbers);

        // Take input for choosing Sorting algorithm
        System.out.println("Select Sorting Method: ");

        int sortingMethod = input.nextInt();

        // Start Sorting
        first.selectAndStartSorting(sortingMethod);

        // Close Scanner
        input.close();

        // Print Sorrted numbers,
        for (int s : first.getArray()) {
            System.out.println(s);
        }

       // Printing sorted array as String
       System.out.println(first.toString(numbers));
    }

}

答案 2 :(得分:0)

我更喜欢 BufferedReader类

假设输入是这样的

1000 999 888 666 5555 333 777 4444 9999 ....................

分隔空格然后使用

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String [] inputBuffer =(br.readLine().split(" "); 

现在你在 inputBuffer 数组中有所有输入值,在你想要的任何数据类型中将它们解析为Long,Integer,Double等

示例:

Integer.parseInt(inputBuffer[i]);

最后应用排序

答案 3 :(得分:0)

Thank you all of you for sharing your experience. I was trying to fix my code base on your answer, but the requirement is to write a construct that accepts a number list(String) a and a sortMethod(int), so I come up with this code


        import java.util.Arrays;

    public class IntegerArraySorting{
        private int[] integerArray;
        int sortingMethod;

        public IntegerArraySo

rting(String listNumber, int method) {
        String[] temp = listNumber.split(" ");
        integerArray = new int[listNumber.length()];
        for (int i = 0; i < temp.length; i++) {
            integerArray[i] = Integer.parseInt(temp[i]);
        }
        sortingMethod = method;
    }

    public void arraySort() {
        switch (sortingMethod) {
        case 1:
            System.out.println("Sorting method: BUBBLE SORT");
            System.out.println("Original list of numbers: ");
            for (int i = 0; i < integerArray.length; i++) {

                 System.out.print(" " + integerArray[i]);
            }
            System.out.println("\rSorted list: ");
            bubbleSort();
            break;
        default:
            System.out.println("Wrong Input");
        }

    }

    public void insertionSort() {
        for (int i = 1; i < integerArray.length; i++) {
            int j = i;
            int B = integerArray[i];
            while ((j > 0) && (integerArray[j - 1] > B)) {
                integerArray[j] = integerArray[j - 1];
                j--;
            }
            integerArray[j] = B;
        }
    }// where array is an array with size = n

    public void bubbleSort() {
        int n = integerArray.length;
        for (int pass = 1; pass < n; pass++) { // count how many times
            // This neintegerArrayt loop becomes shorter and shorter
            for (int i = 0; i < n - pass; i++) {
                if (integerArray[i] > integerArray[i + 1]) {
                    // exchange elements
                    int temp = integerArray[i];
                    integerArray[i] = integerArray[i + 1];
                    integerArray[i + 1] = temp;
                }
            }
        }
    }// where integerArray is an array with size = n

    public void selectionSort() {
        for (int i = 0; i < integerArray.length - 1; i++) {
            for (int j = i + 1; j < integerArray.length; j++) {
                if (integerArray[i] > integerArray[j]) {
                    // ...Exchange elements
                    int temp = integerArray[i];
                    integerArray[i] = integerArray[j];
                    integerArray[j] = temp;
                }
            }
        }
    }// where integerArray is an array with size = n

    public String toString() {
        arraySort();
        String str = Arrays.toString(integerArray);
        return str;
    }

}


and this is my main()





    import java.util.Arrays;
    import java.util.Scanner;

    public class SortingApplication {
        public static void main(String[] args) {
            String listNumber;
            int sortingMethod;

            Scanner keyboard = new Scanner(System.in);

            System.out.println("SortingApplication");
            System.out.println("\t1." + "  " + "Bubble Sort");
            System.out.println("\t2." + "  " + "Insertion Sort");
            System.out.println("\t3." + "  " + "Selection Sort");
            System.out.println("\t4." + "  " + "Exit");
            System.out.println();
            System.out.print("Please enter a number list: ");
            listNumber = keyboard.nextLine();

            System.out.print("Please select a desired method (1), (2), (3), (4): ");
            sortingMethod = keyboard.nextInt();
            System.out.println();

            IntegerArraySorting intarray = new IntegerArraySorting_Luong(listNumber, sortingMethod);
            System.out.println(intarray);
        }
    }


The format of the output suppose to be:

Sorting method: BUBBLE SORT
Original list of numbers: 34 2 15 33 17 8
Sorted list:  2 8 15 17 33 34

but when I run my code, I can't get my original and sorted list in the same line and I get many extra zero:
Please enter a number list: 34 2 15 33 17 8
Please select a desired method (1), (2), (3), (4): 1

Sorting method: BUBBLE SORT
Original list of numbers: 
 34 2 15 33 17 8 0 0 0 0 0 0 0 0 0
Sorted list: 
[0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 8, 15, 17, 33, 34]