我试图使用预定义方法reverse()来反转字符串,该方法在StringBuffer中可用 我从用户那里获取输入,并在打印反向字符串时使用 toString() 方法来避免额外的空格
import java.util.*;
public class Small {
public static void main(String a[])
{
int num;
Scanner sc=new Scanner(System.in);
num = sc.nextInt();
while(num>0)
{
String t;
t=sc.nextLine();
StringBuffer sb=new StringBuffer(t);
sb.reverse();
System.out.println(sb.toString());
num--;
}
}
}
输入:
2
hello
welcome
输出:
<Empty line>
olleh
任何人都可以告诉我为什么会出现这个空白并且也没有得到第二个输出吗?
最佳答案
sc.nextInt()
不会消耗包含数字的行末尾的换行符。
在其后添加 sc.nextLine();
:
num = sc.nextInt();
sc.nextLine();
关于java - 如何在JAVA中修剪StringBuffer中的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52160084/