2017-04-07 32 views
0

我有一個字符串,我需要從列表中放置值,但是當我爲循環列表時,我將在迭代中獲得一個值。從列表中獲取值並插入字符串

public class Test2 { 

    public static void main(String[] args) throws ParseException, JSONException { 

     List<String> value=new ArrayList<String>(); 
     value.add("RAM"); 
     value.add("26"); 
     value.add("INDIA"); 

     for(int i=0;i<value.size();i++){ 
     String template="My name is "+value.get(i) +" age is "+value.get(i)+" country is"+value.get(i); 
     System.out.println(value.get(i)); 
     } 
    o/p should be like this: String ="My name is +"+RAM +"age is "+26+"Country is"+INDIA; 
    } 
} 
+1

歡迎來到Java。使用'StringBuilder'。 –

+0

你的輸出是什麼?你有沒有嘗試改變 –

+0

什麼讓你認爲一個for循環將是一個很好的解決方案? – Thomas

回答

0

發生了什麼事是,在每次迭代中你服用的第i個列表中的元素,並將其放置在String模板的所有位置。

由於@javaguy說,沒有必要使用for循環,如果你只需要在列表中這三個項目,另一種解決方案是使用String.format

String template = "My name is %s age is %s country is %s"; 
String output = String.format(template, value.get(0), value.get(1), value.get(2)); 

這可能是一個有點慢(有趣討論here),但演出似乎與您的情況無關,因此兩種選擇之間的選擇主要基於個人愛好。

1

你並不需要一個for循環,簡單地訪問使用Listindex元素,如下圖所示:

System.out.println("My name is "+value.get(0) + 
    " age is "+value.get(1)+" country is"+value.get(2)); 

另外,我建議你使用StringBuilder用於追加字符串這是一個最好的練習,如下圖所示:

StringBuilder output = new StringBuilder(); 
     output.append("My name is ").append(value.get(0)).append(" age is "). 
      append(value.get(1)).append(" country is ").append(value.get(2)); 
System.out.println(output.toString()); 
+0

感謝它的工作。 – user7352962

0

你不需要任何循環!此外,你不需要任何數組列表,我很抱歉,但我完全理解你所需要的東西,但我這個代碼將幫助您:

List<String> value = new ArrayList<String>(); 
    value.add("RAM"); 
    value.add("26"); 
    value.add("INDIA"); 

    String template = "My name is " + value.get(0) + " age is " + value.get(1) + " country is" + value.get(2); 
    System.out.println(template); 

    // o/p should be like this: String ="My name is +"+RAM +"age is 
    // "+26+"Country is"+INDIA; 
相關問題