如下代码,目的是输出字符串s1与s2 分别所表示的整数的平均数:1 public class Test {
2 static int MAX = 100;
3 static int MIN = 10;
4 public static void main(String[] args) {
5 String s1 = "MAX";
6 String s2 = "MIN";
7 int average = (这里该怎么写?)
8 System.out.println("The average is: " + average);
9 }
10 }第7行该怎么写?
2 static int MAX = 100;
3 static int MIN = 10;
4 public static void main(String[] args) {
5 String s1 = "MAX";
6 String s2 = "MIN";
7 int average = (这里该怎么写?)
8 System.out.println("The average is: " + average);
9 }
10 }第7行该怎么写?
public Object get(Object obj)obj是该field所处对象
public class Test {
static int MAX = 100;
static int MIN = 10;
public static void main(String args[]) throws Exception{
String s1 = String.valueOf(MAX);
String s2 = String.valueOf(MIN);
int average = (Integer.parseInt(s1)+Integer.parseInt(s2))/2;
System.out.println("The average is: " + average);
}
}
3 static int MIN = 10;
min,max是整形的变量名
而
5 String s1 = "MAX";
6 String s2 = "MIN";
min,max是字符串,如果要计算s1,s2,那么就跟2,3行没关系了,支持三楼,可以很好的解决你的问题了
public static void main(String[] args){
String s1 = "MAX";
String s2 = "MIN";
try {
int average = (Integer)Test.class.getDeclaredField(s1).get(null)+(Integer)Test.class.getDeclaredField(s2).get(null);
System.out.println("The average is: " + average);
} catch (Exception e) {
e.printStackTrace();
}
}
你们都理解错这题的意思了,人家只要求修改第七行,这就考虑获取对象了
和第二第三行根本不一样
计算平均值只有
2 static int MAX = 100;
3 static int MIN = 10;
int average = (Integer.parseInt(MAX)+Integer.parseInt(MIN))/2;
是正解。不要抛出异常,采用为average设置缺省更好一点吧。int average = 0;
try {
average = (Integer.parseInt(s1)+Integer.parseInt(s2))/2;
} catch (NumberFormatException e) {
average = ...; //指定一个特殊的缺省值表明解析时发生错误
}