为什么小弟我的代码加上try catch之后反而编译不通过
阅读
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
String ss = in.nextLine();
String[] temp = ss.split(" ");
int person = Integer.parseInt(temp[0]);
int game = Integer.parseInt(temp[1]);
System.out.println("person :"+ person +"game "+ game);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error of Input!");
}
System.out.println(game,person);
}
运行的时候显示找不到person和game,小白求解
------解决方案--------------------
public static void main(String[] args) {
int person=0;
int game =0;
try {
Scanner in = new Scanner(System.in);
String ss = in.nextLine();
String[] temp = ss.split(" ");
person = Integer.parseInt(temp[0]);
game = Integer.parseInt(temp[1]);
System.out.println("person :"+ person +"game "+ game);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error of Input!");
}
System.out.println(game,person);
}
这样就行了 ,作用域的问题。
------解决方案--------------------
System.out.println(game,person); 看看api 没有 2个 参数的。
其次 ,你 game,person 也访问不到 ,变量的作用范围 不一样 。
------解决方案--------------------
作用域问题person,game在try以外都访问不到, 你这样写
public static void main(String[] args) {
int person,game;
try {
Scanner in = new Scanner(System.in);
String ss = in.nextLine();
String[] temp = ss.split(" ");
person = Integer.parseInt(temp[0]);
game = Integer.parseInt(temp[1]);
System.out.println("person :"+ person +"game "+ game);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error of Input!");
}
System.out.println(game,person);
}
阅读