哨兵控制的循环 + 数组



我对编程很陌生,我正在尝试创建一个程序,该程序将要求哨兵控制的循环中的用户输入单词。
输入所有单词后,程序应按字母顺序与原始顺序并排显示它们。

现在我正在尝试创建具有用户输入确切长度的 userWords 数组(最多 20 个)的副本,以便可以对其进行排序(无法对空值进行排序)。

我有问题。
任何帮助不胜感激!

import java.util.Arrays;
import java.util.Scanner;
public class AlphabeticalWords {
    public static void main(String[] args) {
        int counter = 0;
        String [] userWords= new String[20];
        String[] myCopyArray=getArrayCopy(userWords);
        myCopyArray[counter];

        Scanner input= new Scanner(System.in);
        for (counter=0; counter< userWords.length; counter++){
            System.out.println("Please enter a word or Crl-D to stop");
            while (input.hasNext()){
                userWords[counter]=input.next();
                System.out.println("Please enter a word or Crl-D to stop");
                counter++;
            }
        }
                //System.arraycopy(userWords);
                //Arrays.sort(userWords);
                //printArrayElements(userWords);
    }
    public static void printArrayElements( String[] anyArray){
        for(int index=0; index< anyArray.length; index++){
            System.out.println(anyArray[index]);
        }
    }

请看这里。

已完成的更改

1.) 当使用 for 循环时,不需要 while 循环。

2.) 用于System.arraycopy(userWords, 0, newArray, 0, userWords.length);复制数组。

3.) 维护两个数组,原始数组和复制数组,在复制数组上完成排序。

4.) 最后两个阵列都打印了。

public static void main(String[] args) {
        int counter = 0;
        String[] userWords = new String[5];
        Scanner input = new Scanner(System.in);
        for (counter = 0; counter < userWords.length; counter++) {
            System.out
                    .println("Please enter a word or Crl-D to stop" + counter);
            userWords[counter] = input.nextLine();
        }
        String[] myCopyArray = getArrayCopy(userWords);
        Arrays.sort(myCopyArray);
        printArrayElements(userWords, myCopyArray);
    }
    private static String[] getArrayCopy(String[] userWords) {
        String[] newArray = new String[userWords.length];
        System.arraycopy(userWords, 0, newArray, 0, userWords.length);
        return newArray;
    }
    public static void printArrayElements(String[] originalArray,
            String[] sortedArray) {
        for (int index = 0; index < originalArray.length; index++) {
            System.out.println(originalArray[index] + " :: "
                    + sortedArray[index]);
        }
    }

输出

Please enter a word or Crl-D to stop0
asd
Please enter a word or Crl-D to stop1
asda
Please enter a word or Crl-D to stop2
werw
Please enter a word or Crl-D to stop3
efgv
Please enter a word or Crl-D to stop4
qe
asd :: asd
asda :: asda
werw :: efgv
efgv :: qe
qe :: werw

最新更新