java逆序英文句子中的單詞順序
阿新 • • 發佈:2019-02-04
題目要求:給定n行的英文句子,要求輸出句子中逆序單詞後的句子,如:
輸入:n=3
I love you
How are you
My name is Liming
輸出:
you love I
you are How
Liming is name My
依據Java語言給我們提供的拆分空格間隔的單詞的方法(split(" ")),倒序輸出即可;
import java.util.Scanner; public class Main { public static String reverseWords(String sentence) { StringBuilder sb = new StringBuilder(sentence.length() + 1); String[] words = sentence.split(" "); for (int i = words.length - 1; i >= 0; i--) { sb.append(words[i]).append(' '); } sb.setLength(sb.length() - 1); return sb.toString(); } public static void main(String[] args) throws UnsupportedEncodingException { Scanner in= new Scanner(System.in); System.out.printf("Please input how many lines you want to enter: "); String[] input = new String[in.nextInt()]; in.nextLine(); for (int i = 0; i < input.length; i++) { input[i] = in.nextLine(); } System.out.printf("\nYour input:\n"); for (String s : input) { System.out.println(reverseWords(s)); } } }