如何根据用户输入访问对象的属性?
例如我的班级是
class A{
public String a;
public String b;
//constructor
A(){
a="first";
b="second";
}
}
主程序是
public static void main(String[] args) {
A a=new A();
Scanner in= new Scanner(System.in);
String x=in.next(); // the input it will be "a";
String y= a.x;
System.out.println(y);
x=in.next(); // the input it will be "b";
y= a.x;
System.out.println(y);
}
答案 0 :(得分:0)
尝试以下操作,您只需测试输入内容:
public static void main(String[] args) {
A a=new A();
Scanner in= new Scanner(System.in);
String x=in.next();
if(x.equals("a")){ // the input is "a";
String y= a.a;
System.out.println(y);
}
else if(x.equals("b")){ // the input is "b";
String y= a.b;
System.out.println(y);
}
else System.out.println("Input a or b please !!!");
}
如果您编写a.x
,编译器将获取x
作为类A
的变量,而不是输入值。
答案 1 :(得分:-1)
import java.lang.reflect.*;
import java.util.*;
class A{
public String a;
public String b;
//constructor
A(){
a="first";
b="second";
}
public static void main(String[] args) throws Exception {
A a=new A();
Class c = A.class;
Scanner in= new Scanner(System.in);
String x=in.next(); // the input it will be "a";
Field f = c.getField(x);
String y = (String) f.get(a);
System.out.println(y);
x=in.next(); // the input it will be "b";
f = c.getField(x);
y = (String) f.get(a);
System.out.println(y);
}
}