標籤:寫法 imp 表達 長度 util next system.in for generate
第六周編程題
依照學術誠信條款,我保證此作業是本人獨立完成的。
1
單詞長度(4分)
題目內容:
你的程式要讀入一行文本,其中以空格分隔為若干個單詞,以‘.’結束。你要輸出這行文本中每個單詞的長度。這裡的單詞與語言無關,可以包括各種符號,比如“it‘s”算一個單詞,長度為4。注意,行中可能出現連續的空格。
輸入格式:
輸入在一行中給出一行文本,以‘.’結束,結尾的句號不能計算在最後一個單詞的長度內。
輸出格式:
在一行中輸出這行文本對應的單詞的長度,每個長度之間以空格隔開,行末沒有最後的空格。
輸入範例:
It‘s great to see you here.
輸出範例:
4 5 2 3 3 4
時間限制:500ms記憶體限制:32000kb
import java.util.Scanner; public class hello{public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);String s=in.next();char ch=‘.‘;while (s.length()>0)//採用分別讀入每一個單詞進行,//缺陷是如果語句中間輸入的單詞未尾是“.”就會視為語句結束,該寫法未考慮有這種情況。{if(s.charAt(s.length()-1)==ch){System.out.print((s.substring(0, s.length()-1)).length());break;}else{System.out.print(s.length()+" ");s=in.next();}}}}
方法二(更標準):
import java.util.Scanner; public class hello{public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);String s=in.nextLine();char ch=‘.‘;String[] word=s.split("\\s{1,}");//Regex,一個或一個以上的空格for(int i=0;i<word.length-1;i++){System.out.print(word[i].trim().length()+" ");//用Regex後,trim()可以不要}String wend=word[word.length-1].trim();if(wend.charAt(wend.length()-1)==ch){System.out.print(wend.substring(0, wend.length()-1).length());}}}
程式設計入門—Java語言 第六周編程題 1 單詞長度(4分)