static void Main(string[] args) { const int n = 100; Book[] bk = new Book[n] ; Random ran = new Random(); for (int i = 0; i < n; i++) { int RandKey = ran.Next(0, 2);//左闭右开 if (RandKey == 0) bk[i] = new Book("Computer"); else bk[i] = new Book("English"); } for(int i=0;i<n;i++) { if(bk[i].kind[0]=='C') bk[i].setStrategy( new ComputerStrategy() ); else bk[i].setStrategy(new EnglishStrategy()); bk[i].operation(); } 用Java写
时间: 2024-02-14 17:35:20 浏览: 271
public static void main(String[] args) {
final int n = 100;
Book[] bk = new Book[n];
Random ran = new Random();
for (int i = 0; i < n; i++) {
int RandKey = ran.nextInt(2);
if (RandKey == 0) {
bk[i] = new Book("Computer");
} else {
bk[i] = new Book("English");
}
}
for (int i = 0; i < n; i++) {
if (bk[i].getKind().charAt(0) == 'C') {
bk[i].setStrategy(new ComputerStrategy());
} else {
bk[i].setStrategy(new EnglishStrategy());
}
bk[i].operation();
}
}
相关问题
public static void main(String[] args) { int i = 1 / 0; }
As an AI language model, I can tell you that this code will result in an ArithmeticException being thrown at runtime because dividing any number by zero is an undefined operation in mathematics. Therefore, the result cannot be computed and will throw an exception.
class demo{public static void main(int x=div(1,2}
在这个问题里,需要对Java语言的语法和调用函数的方式有一定的了解。
首先,在Java中,main方法的参数是一个字符串数组,而不是一个整数。另外,在方法参数的定义中不可以给参数一个默认的初始值。
在这个例子中,如果要调用一个div函数并将结果赋值给x,首先需要定义一个div函数。假设div函数是一个可以接受两个整数参数并返回它们相除的函数,那么它的定义可能是这样的:
public static int div(int a, int b){
return a / b;
}
然后,在main方法中调用div函数,并将结果赋值给x,可以这样写:
public static void main(String[] args){
int x = div(1, 2);
}
上面的代码中,main方法接受一个字符串数组参数args。在方法体内部,使用div(1, 2)的结果赋值给x。这样x的值就是1除以2的结果,即0。
综上所述,能正确执行的代码应该是:
public class demo{
public static int div(int a, int b){
return a / b;
}
public static void main(String[] args){
int x = div(1, 2);
}
}
希望以上内容能够解答您的问题。如有其他疑问,欢迎继续询问。