繁体   English   中英

Palindrome 程序适用于单个测试用例,但在其他情况下继续输入

[英]Palindrome program works fine for a single test case but keeps taking input otherwise

public static void main(String[] args) {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int test_cases = Integer.parseInt(br.readLine());
        if (test_cases >= 1 && test_cases <= 20) {
            String[] ans = new String[test_cases];
            for (int i = 0; i < test_cases; i++) {
                char[] n = br.readLine().toCharArray();
                int k = 0;
                int j = n.length - 1;
                while (k <= j) {
                    if (n[k] == n[j]) {
                        k++;
                        j--;
                        ans[i] = "wins";
                    }
                    else
                        ans[i] = "loses";
                }
            }
            for (String s : ans)
                System.out.println(s);
        }
    }
    catch (Exception x) {
    }
}

问题陈述:输入的第一行包含一个 integer T,即测试用例的数量。 接下来是包含 integer N 的 T 行。对于每个输入 output,如果数字是回文则“赢”,如果不是回文,则在新行中“输”。

对于 test_cases=1,程序运行良好,但对于 test_cases>1,程序继续接受输入。 我已经解决了回文问题,但我仍然无法理解这段代码有什么问题。 谁能向我解释为什么它一直在接受输入?

对于非回文,您的代码在无限循环中运行。 只需为此添加休息时间。

while (k <= j) {
    if (n[k] == n[j]) {
        k++;
        j--;
        ans[i] = "wins";
    }
    else {
        ans[i] = "loses";
        break;
    }
}

这可以是解决方案之一。

public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int test_cases = Integer.parseInt(br.readLine());
            if (test_cases >= 1 && test_cases <= 20) {
                for (int i = 0; i < test_cases; i++) {
                    char[] n = br.readLine().toCharArray();
                    int k = 0;
                    int j = n.length - 1;
                    boolean flag=false;
                    while (k <= j) {
                        if (n[k] == n[j]) {
                            k++;
                            j--;
                            flag=true;
                        }
                        else{
                            flag=false;
                            break;
                        }
                    }
                    if(flag)    System.out.println("wins");
                    else    System.out.println("loses");
                }
            }
        }
        catch (Exception x) {
        }
    }

对于不是回文的字符串,您的循环将无限运行。 此外,您不需要将所有测试用例的结果存储在一个数组中,您可以每次为每个测试用例打印它。 但是,如果您打算稍后存储字符串并显示结果,则可以使用类似 StringBuffer 类的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM