print many values by a loop in java

时间:2018-05-14 17:34:18

标签: java

public class teste {

public static void main(String[] args) {
    int t1=5;
    int t2=10;
    int t3=30;

    for(int i=1;i<4;i++)
    {
        System.out.println("t"+i);
    }

}}

Hi guys I don't know if it exists in java but I wanna print t1 t2 t3 by a loop, for example for i=1 t(i=1) => t1 so it will give us 5, how can I do that, and thank you all.

5 个答案:

答案 0 :(得分:3)

3 variables mean three atomic statements are required but to access them in continuous way , collect them in some container like array so use

int t1=5;
int t2=10;
int t3=30;
int[] arr = {t1,t2,t3}; // array index start from 0
//           0  1  2
// arr[0] is 5
// arr[1] is 10 and so on

for(int i=0;i<3;i++)
{
    System.out.println(arr[i]);
}

Other option: use var args which is still sort of an array but flexible like

static void printNums(int... arr){
    for(int i=0;i<arr.length;i++)
    {
        System.out.println(arr[i]);
    }
}

and call it like

printNums(t1,t2);
printNums(t1,t2,t3);
printNums(1,2,3,4,5,6);

答案 1 :(得分:1)

There is no way to call a variable using String or int or whatever

But that's the purpose of arrays, first index is 0 and last one is length-1 (here 2)

int[] t = new int[]{5, 10, 30};

for(int i=0 ; i<t.length ; i++){
    System.out.println(t[i]);
}
// gives
5
10
30

答案 2 :(得分:0)

for循环仅打印值t1,t2,t3,因为您将t1初始化为变量,而在输出中,您通过包含引号将其用作文本。 试试这段代码。

public class test
{
    public static void main(String[] args) {
        int [] arrValue = {5 , 10 , 30};

        for(int i= 0; i <4; i++)
        {
            System.out.println("t"+i + "=" + arrValue[i]);
        }
    }
}

答案 3 :(得分:0)

可以将"t" + i视为密钥(而不是不受支持的动态变量名称)吗?如果符合上下文,则可以使用Map。例如:

public static void main(String[] args) {
    Map<String, Integer> tVals = new HashMap<>();
    tVals.put("t1", 5);
    tVals.put("t2", 10);
    tVals.put("t3", 30);

    for (int i = 1; i < 4; i++) {
        System.out.println(tVals.get("t" + i));
    }
}

答案 4 :(得分:-1)

如果我不理解您的问题,请告诉我。 你似乎要尝试的是打印t1 t2和t3,但是基于for循环的i对吗?所以你认为t + i首先应该是t1,然后是t2然后是t3,最后输出这些值。这对任何语言都不起作用。首先,t是char,而1 2或3是整数。其次,如果你把它放在System.out.println中那么它基本上意味着“打印出t然后我”,而不是“打印出t + i将是什么(初始化)”。我可能不太清楚解释。无论如何,你应该使用数组。

尝试以下方法:

class test{

    public static void main(String[] args) {

        int[] anArray = { 
        5, 10, 30,
    };

        for(int i = 0; i < anArray.length; i++)
        {
            System.out.println(anArray[i]);

        }
    }

}