Java 初始化运行参数
程序员文章站
2024-03-04 22:02:00
...
初始化运行参数
1. 初始化 Java 运行参数
- Run > Edit Configuration > Program Arguments;
2. 异常的处理
public class test {
public static void main(String[] args) {
try {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]);
System.out.println("x: " + x);
System.out.println("y: " + y);
System.out.println("z: " + z);
} catch (ArrayIndexOutOfBoundsException e) {//没有输入参数时报错
e.printStackTrace();
} catch(NumberFormatException e){//输入参数的格式异常,即不是数字时报错
e.printStackTrace();
}
}
}
3. 应用——工厂模式
- Program Arguments:apple;
interface Fruit {
public void eat();
}
class Apple implements Fruit {
public void eat() {
System.out.println("吃苹果。");
}
}
class Orange implements Fruit {
public void eat() {
System.out.println("吃橘子。");
}
}
class Factory1 { // 此类不需要维护属性的状态
public static Fruit getInstance(String className) {
if ("apple".equals(className)) {
return new Apple();
}
if ("orange".equals(className)) {
return new Orange();
}
return null;
}
}
public class Factory {
public static void main(String args[]) {
Fruit f = Factory1.getInstance(args[0]); // 初始化参数
f.eat();
}
}