无法在屏幕上显示输出

时间:2020-03-19 17:09:51

标签: java arrays string

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int testCases = sc.nextInt();
        String[] bigNames = new String[testCases];

        while(testCases != 0)
        {
            int noOfNames = sc.nextInt();
            sc.nextLine();
            String[] names = new String[noOfNames];
            for(int i = 0; i<noOfNames; i++)
                names[i] = sc.nextLine();

            for(int i = 0; i<noOfNames-1;i++)
                if(names[i].length() > names[i+1].length())
                {
                    String temp = names[i];
                    names[i] = names[i+1];
                    names[i+1] = temp;
                }

            bigNames[testCases-1] = names[noOfNames-1];
            testCases--;
        }
        for(int i = testCases-1; i >= 0; i--)
            System.out.println(bigNames[i]);

    }
}
2
3
Vjhhjg
Gjbh
Vhb
2
-gbhg
Bbb

程序在这里完成,无需最后打印循环 * / **

1 个答案:

答案 0 :(得分:0)

我不确定您要执行的操作,您应该告诉我们您希望此代码执行的操作。 无论如何,我会尽力帮助您
while(testCases != 0)

将持续到testCases为0为止。

        for(int i = testCases-1; i >= 0; i--)
        System.out.println(bigNames[i]);

将永远不会运行,因为在循环开始时我为-1。

您可以做的是:

    Scanner sc = new Scanner(System.in);

    int testCases = sc.nextInt();
    int j = testCases;
    String[] bigNames = new String[testCases];

    while(j != 0)
    {
        int noOfNames = sc.nextInt();
        sc.nextLine();
        String[] names = new String[noOfNames];
        for(int i = 0; i<noOfNames; i++)
            names[i] = sc.nextLine();

        for(int i = 0; i<noOfNames-1;i++)
            if(names[i].length() > names[i+1].length())
            {
                String temp = names[i];
                names[i] = names[i+1];
                names[i+1] = temp;
            }

        bigNames[j-1] = names[noOfNames-1];
        j--;
    }
    for(int i = testCases-1; i >= 0; i--)
        System.out.println(bigNames[i]);
}
相关问题