首页 > 解决方案 > Java 项目输出

问题描述

嗨,我正在完成一项作业,但是我得到了错误的输出。

该项目的目标是反转字符串。

所以它应该将一行文本作为输入,并反向输出该行文本。程序重复,当用户输入“完成”、“完成”或“d”作为文本行时结束。

例如:如果输入是:

Hello there
Hey
done

输出是:

ereht olleH
yeH

我的代码:

import java.util.Scanner;

public class LabProgram {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        String str;
        while (true) {
            str = scnr.nextLine();
            if (str.equals("quit") || str.equals("Quit") || str.equals("q")) break;
            for (int i = 0; i < str.length(); i++) {
                System.out.print(str.charAt(str.length() - i - 1));
            }
            System.out.println();
        }
    }
}

我当前的代码是,但是输出返回为:

输入

Hello there
Hey
done

输出

ereht olleH
yeH
enod

预期产出

ereht olleH

无法弄清楚我做错了什么。

标签: javastring

解决方案


    /*
        I don't know what you know, so I am not sure how your professor
        wants you to complete this, but I will do what comes to mind for myself.
    */

    //Instead of while(true) I like to use do while, which runs once automatically, and continues running until a condition is met
    do {
        str = scnr.nextLine();
        int i = 0;

        //This isn't the cleanest way to solve this, especially because it doesn't remove the space before done.
        //You could add more if statements for that, but the cleanest way would be to split the words into a String array
        // and check if any of the values of the array equal done, and remove it before flipping it around
        if(str.toLowerCase().contains("done"))
            i = 4;
        else if(str.toLowerCase().contains("d"))
            i = 1;

        while (i < str.length()) {
            System.out.print(str.charAt(str.length() - i - 1));
            i++;
        }
        System.out.println();
    }
    while (!str.toLowerCase().contains("done") || !str.toLowerCase().contains("d")); //This replaces that if statement from before

推荐阅读