Java For loop within an array list
Im a beginner in java and starting to do test driven development. I have a pretty basic scenario i am stuck with. I want to pass a string of numbers from 1 to x. i.e if x is 3, it will return "1, 2, 3" or if x is 5, it will return "1, 2, 3, 4, 5".
I know that i need 开发者_JAVA百科to use an array list and a for loop but am stuck with the syntax. Someone please help!
Thanks
Try the following code:
int x = 5;
StringBuilder sb = new StringBuilder(); //You need import java.util.StringBuilder
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i!=x) {
sb.append(',');
}
}
String result = sb.toString(); //Here will be "1,2,3,4,5"
Here's a start:
String output = "";
int x = 5;
for (int i=1; i<=5; i++)
{
output += i + ", ";
}
System.out.println(output);
// prints the string "1, 2, 3, 4, 5, "
String s = "";
int x = 5;
for(int i = 1; i <= x; i++) s += i + (i!=x?", ":"");
System.out.println(s); // It prints "1, 2, 3, 4, 5"
If it is a requirement to use array lists you can use the "add" and "get" methods in ArrayList:
List<Integer> listOfIntegers = new ArrayList<Integer>();
int = 5;
String stringOfIntegers = "";
for (int i = 1; i <= 5; i++) {
listOfIntegers.add(i);
}
for (int i = 0; i < 5; i++) {
stringOfIntegers += listOfIntegers.get(i);
stringOfIntegers += ",";
}
System.out.println(stringOfIntegers);
ADDED: [Returned from a method]
public String numberString(){
List<Integer> listOfIntegers = new ArrayList<Integer>();
int = 5;
String stringOfIntegers = "";
for (int i = 1; i <= 5; i++) {
listOfIntegers.add(i);
}
for (int i = 0; i < 5; i++) {
stringOfIntegers += listOfIntegers.get(i);
stringOfIntegers += ",";
}
return stringOfIntegers;
}
[Returned from a method where you tell it what number to count to]
public String numberString(int maxNumber){
List<Integer> listOfIntegers = new ArrayList<Integer>();
String stringOfIntegers = "";
for (int i = 1; i <= maxNumber; i++) {
listOfIntegers.add(i);
}
for (int i = 0; i < 5; i++) {
stringOfIntegers += listOfIntegers.get(i);
stringOfIntegers += ",";
}
return stringOfIntegers;
}
So for instance if you pass in a value of "7" the returned string will be: "1,2,3,4,5,6,7". To "invoke" this method you can use something like:
public static void main(String[] args){
MyClass myClass = new MyClass(); //This will be the name of the class you created
String myNumberString = myClass.numberString(6);
System.out.println("My number string is: " + myNumberString); //This will print: "1,2,3,4,5,6"
}
精彩评论