2017-04-07 30 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; 
相关问题