学过java的朋友进来帮帮忙啊

来源:百度知道 编辑:UC知道 时间:2024/06/15 02:31:23
要写一个程序,要求是使用者输入一段string,然后程序要把这段string的第二个word输出,如果只有一个word,就输出only one word.比如说:
enter string:my favourite computer
second word is "favourite";

import java.util.Scanner;

public class StringPicker {

public static String getSecondWord(String str) {
String word = null;
String[] strs = str.split(" ");// 用空格分割字符串
if (strs.length > 1) {
word = strs[1];// 取第二个word
}
return word;
}

public static void input() {
Scanner sc = new Scanner(System.in);
String str;
// 如果使用者不输入字符串则循环提示"enter string:"
// 直到用户输入为止
do {
System.err.print("enter string:");
str = sc.nextLine();
} while (str.length() == 0);
String result = getSecondWord(str);
if (result == null) {
System.err.println("only one word");
} else {
System.err.println("second word is \"" + result + "\"");
}
}

public static void main(String[] args) {
input();// 调用执行
}
}

import java.io