2011-03-08 63 views
0

假設行是字符串數組(如下面的向後應用程序中所示)。寫一個for循環,在列中打印數組中字符串的長度,從數組中最後一個條目的長度開始,以數組元素的第0位結束。打印數組中的字符

例如,if線路由這三個字符串:

現在是
所有好男人的時間

你的代碼應該打印:

如何打印在陣列中的字符數?我試過這個問題至少20次無濟於事!請幫忙!

import java.util.*; 

public class Backwards { 
    public static void main(String[] args) { 
     String[] lines = new String[50]; 
     Scanner scan = new Scanner(System.in); 
     int pos = 0; 
     String t = " "; 

     while(t.length() > 0){ 
      t = scan.nextLine(); 
      lines[pos] = t; 
      pos++; 
     } 

     for(int j = pos - 1; j >= 0; j--){ 
      lines[j] = lines[j].toUpperCase(); 
      System.out.println(lines[j]); 
     } 
    } 
} 
+1

不應該這樣下'homework'被標記? – 2011-03-08 02:58:35

+0

您的代碼正在顛倒該數組中的字符串的內部。你確定你想以相反的方式獲取每行中的字符數嗎?如果是的話,請閱讀下面的答案... – 2011-03-08 03:06:36

回答

1

這顯然是一種分配,所以我不會爲你寫代碼,但我會給你足夠的提示讓你走上正確的軌道。

您可以在數組中的字符串上反向循環,隨時打印每個字符串的長度(您已經有了正確的反向循環)。

String對象的length() method應該是在你的println興趣;-)

0

,你應該打印線[J]。長度(),否則,你會打印出輸入字符串。
此外,使用arrayList將會更加方便。

0
1) Define an ArrayList, say arrLines. 
2) Read each line of the input, convert to string, if required using .toString();and 
    a)Calculate string length: strLength = <stringName>.length() 
    b)Add the length calculated in step a) to arrLines : arrLines.add(strLength); 
3) Print the arrLines in reverse: 
for(int i=arrLines.size();i>0;i--) 
{ 
    System.out.println(" "+arrLines.get(i)); 
} 
1

想想倒退:

for(int i = lines.length-1; i>=0; i--){ //starts the loop from the last array 
    System.out.println(lines[i].length()); //prints out the length of the string at that index 
}