Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single line with several words. There will be at most 1000 characters in a line.
Output
For each test case, you should output the text which is processed.
Sample Input
3 olleh !dlrow m’I morf .udh I ekil .mca
Sample Output
hello world! I’m from hdu. I like acm.
Hint
Remember to use getchar() to read ‘\n’ after the interger T, then you may use gets() to read a line and process it.
大概的意思就是:
给出一个整数n,接下来输入n行字符串,然后每行字符串按照空格取每一个单词,然后将每个单词逆序输出
题目很简单,因此在这里直接贴代码,讲一下自己遇到的问题:
import java.util.Scanner;
public class Main {
public static String reverse1(String s) {
int length = s.length();
if (length <= 1)
return s;
String left = s.substring(0, length / 2);
String right = s.substring(length / 2, length);
return reverse1(right) + reverse1(left);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int num = in.nextInt(); // 这里进行整数输入n 标注为:1
String str;
in.nextLine(); // 这里开始没有加,出现了问题 标注为:2
for (int i = 0; i < num; i++) {
str = in.nextLine(); // 这里就是用来输入整行字符串 标注为:3
String[] s = str.split(" ");
for (int j = 0; j < s.length; j++) {
if (j != s.length - 1)
{
String ss = reverse1(s[j]);
System.out.print(ss + " ");
}
else
{
String ss = reverse1(s[j]);
System.out.print(ss);
int p = str.length() - 1;
while (str.charAt(p) == ' ') {
System.out.print(' ');
p--;
}
System.out.println();
}
}
}
}
}
}