Reputation: 7
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.
Upvotes: 0
Views: 171
Reputation: 11
The for loop will only print the values t1, t2,t3 only because you initialized the t1 as a variable and in your output you using it as a text by including quotation marks. Try this code.
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]);
}
}
}
Upvotes: 0
Reputation: 2801
Can "t" + i
be considered a key (instead of a dynamic variable name which is not supported)? If that fits the context then a Map could be used. For example:
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));
}
}
Upvotes: 0
Reputation: 31
Please tell me if I don't understand your question. What you seem to be trying is to print t1 t2 and t3, but based on the i of the for loop right? So you think that t + i should first be t1, then t2 then t3 and finally output those values. That doesn't work for any language this way. First of all, t is a char, while 1 2 or 3 is an integer. Secondly, if you put it like that in System.out.println it basically means "print out t and then i", instead of "print out what t+i would be (as initialized)". I might not be very clear with explaining. Anyway, you should use an array.
Try the following:
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]);
}
}
}
Upvotes: -1
Reputation: 37414
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);
Upvotes: 3
Reputation: 54168
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
Upvotes: 1