[英]How do I declare a variable with an array element?
I have an array of elements and I want to use the elements in the array as variables. 我有一个元素数组,我想将数组中的元素用作变量。
I want to do this because I have an equation, the equation requires multiple variable inputs, and I want to initialize an array, iterate through it, and request input for each variable (or each element of the array). 我要这样做是因为我有一个方程式,该方程式需要多个变量输入,并且我想初始化一个数组,遍历它,并为每个变量(或数组的每个元素)请求输入。
So I have an array like this: 所以我有一个像这样的数组:
String variableArray[] = {"a", "b", "c"}
And now I'm iterating through this array and getting the input from the user: 现在,我遍历此数组并从用户那里获取输入:
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
int variableArray[i] = keysIn.nextInt();
}
The problem is this line doesn't compile: 问题是此行无法编译:
int variableArray[i] = keysIn.nextInt();
In essence, I want to use the elements of the array variableArray[] (ie a, b, and c) as variables so I don't have to do the same process for each variable. 本质上,我想将变量variableArray []的元素(即a,b和c)用作变量,因此不必为每个变量执行相同的过程。 I can't imagine how it's done when there are many variables to input (I wouldn't want to type that all out).
我无法想象当有很多变量要输入时我是怎么做的(我不想全部输入)。
tl;dr I want to streamline the process of inputting values for multiple variables. tl; dr我想简化为多个变量输入值的过程。
You initialized your array as: 您将数组初始化为:
String variableArray[] = {"a", "b", "c"}
ie an array of String
s. 即
String
的数组。
If you want to refer later to the i
-th element, you just write: 如果要稍后引用第
i
-th个元素,只需编写:
variableArray[i]
without any int
before - you can't initialize single entries in a array. 之前没有任何
int
您无法初始化数组中的单个条目。
Two things; 两件事情;
Firstly you've declared your array as and array of String
s so variableArray[i] = keysIn.nextInt()
won't work any way, int
can't be stored in a String
array. 首先,您将数组声明为和
String
的数组,因此variableArray[i] = keysIn.nextInt()
不能以任何方式工作, int
不能存储在String
数组中。
Secondly, int variableArray[i] = keysIn.nextInt();
其次,
int variableArray[i] = keysIn.nextInt();
is incorrect, because variableArray
has already been declared (as a String
array and variableArray[i]
is a String
element of that array) 是错误的,因为已经声明了
variableArray
(作为String
数组,而variableArray[i]
是该数组的String
元素)
The line should read variableArray[i] = keysIn.next();
该行应读取
variableArray[i] = keysIn.next();
, but this will store the text the user has entered, not a numerical value. ,但这将存储用户输入的文本,而不是数字值。
What it could look like is... 它看起来像是...
String labelArray[] = {"a", "b", "c"}
int variableArray[] = new int[3];
// You could declare this as
// int variableArray[] = {0, 0, 0};
// if you wanted the array to be initialized with some values first.
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", labelArray[i]);
variableArray[i] = keysIn.nextInt();
}
UPDATED 更新
int a = variableArray[0];
int b = variableArray[1];
int c = variableArray[2];
Java doesn't work like that. Java不能那样工作。
"a"
is a string literal, and you can't use it as if it were a variable. "a"
是字符串文字,您不能像将其用作变量一样使用它。 There's no magical way to go from having an array element whose value is "a"
to having an int
variable called a
. 从拥有一个值为
"a"
的数组元素到拥有一个称为a
的int
变量,没有任何神奇的方法。
There are, however, some things you can do that are probably equivalent to what you want. 但是,您可以执行某些操作,这些操作可能等于您想要的。
String variableArray[] = {"a", "b", "c"}
int valueArray[] = new int[variableArray.length];
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
valueArray[i] = keysIn.nextInt();
}
To get the value of "a"
, do valueArray[0]
. 要获取值
"a"
,请执行valueArray[0]
。
Here's another more sophisticated suggestion: 这是另一个更复杂的建议:
String variableArray[] = {"a", "b", "c"}
HashMap<String, Integer> variableValues = new HashMap<String, Integer>();
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
variableValues.put(variableArray[i], keysIn.nextInt());
}
To get the value of "a"
, do variableValues.get("a")
. 要获取
"a"
的值,请执行variableValues.get("a")
。
What you are actually looking for is a Map . 您实际上正在寻找的是地图 。 It's a collection of mappings from one value to another value.
它是从一个值到另一个值的映射的集合。 In your case, you can use it to assign an integer value (the value of a variable) to a string that represents the name of a variable.
在您的情况下,可以使用它为代表变量名的字符串分配一个整数值(变量的值)。
Therefore you would create an instance of a Map<String, Integer>
- read "a map from String to Integer". 因此,您将创建
Map<String, Integer>
的实例-阅读“从String到Integer的映射”。
See this tutorial for details on the subject. 有关此主题的详细信息,请参见本教程 。
Now what would your code look like with it: 现在,您的代码将是什么样子:
String[] variableNames = { "a", "b", "c" };
// create the map object
Map<String, Integer> variableValues = new LinkedHashMap<String, Integer>();
// read variable values and put the mappings into the map
for (int i = 0; i < variableNames.length; i++) {
System.out.printf("Enter value for %s: ", variableNames[i]);
variableValues.put(variableNames[i], keysIn.nextInt());
}
// print value of each variable
for (int i = 0; i < variableNames.length; i++) {
String varName = variableNames[i];
System.out.println(varName + " = " + variableValues.get(varName));
}
Output: 输出:
Enter value for a: 5
Enter value for b: 4
Enter value for c: 8
a = 5
b = 4
c = 8
Please use with caution, but after reading your comments to the other answers, you might get a little closer to the way you want it using reflection: 请谨慎使用,但在阅读对其他答案的评论后,您可能会更接近使用反射的方式:
import java.lang.reflect.Field;
import java.util.Scanner;
public class VariableInput {
public static class Input {
public int a;
public int b;
public int c;
}
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException {
Scanner keysIn = new Scanner(System.in);
Field[] fields = Input.class.getDeclaredFields();
Input in = new Input();
for (int i = 0; i < 3; i++) {
System.out.printf("Enter value for %s: ", fields[i].getName());
fields[i].set(in, keysIn.nextInt());
}
int d = in.a + in.b + in.c;
System.out.println("d=" + d);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.