gpt4 book ai didi

java - 反转java中的每一行输入

转载 作者:太空宇宙 更新时间:2023-11-04 12:45:03 25 4
gpt4 key购买 nike

我的代码无法反转输入的每一行。它应该看起来像:输入:

abc
def
ghi

输出:

cba
fed
ihg

如何修改?

import java.*;
import java.util.Scanner;

public class Reverse {
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
String s = new String();

while (in.hasNextLine()) {
s += in.nextLine() + "\n";
}

StringBuffer r = new StringBuffer(s);
r = r.reverse();
System.out.println(r);
}
}

最佳答案

您正在反转字符串中的字符。您需要反转每行上的字符。

Scanner in = new Scanner(System.in);
String s = new String();

while(in.hasNextLine()){
StringBuffer buf = new StringBuffer(in.nextLine());
s += buf.reverse() + "\n";
}
System.out.println(s);

关于java - 反转java中的每一行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36415561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com