一、选择题
(1)下列对整形常量i 的定义中,正确的是(C)
A.final i;
B.static int i;
C.static final int i=234;
D.final float i=3.14f;
题目要求定义整形常量,A没有指定类型,B选项定义的是变量,D选项定义的是浮点类型
(2)下列程序的运行结果是(B)
public static void main(String[] args) {
String str1="hello";
String str2="he"+new String("llo");
System.out.println(str1==str2);
}
A.true
B.false
C.exception
D.无输出
str1和str2这两个引用中所保存的内存地址是不同的
(3)下列程序的运行结果()
public void getCustomerInfo(){
try{
//do something that may cause an Exception
}catch (java.io.FileNotFoundException e){
System.out.print("FileNotFoundException ");
}catch (java.io.IOException e){
System.out.print("IOException ");
}catch (java.lang.Exception e){
System.out.print("Exception");
}
}
A.IOException
B.IOExceptionException
C.FileNotFoundExceptionException
D.FileNotFoundExceptionIOException Exception
对于一个程序来说不可能一次抛出多个异常,因此只有A选项只抛出了一种异常,因此选择A
(4)如下代码,执行test函数后,屏幕的打印结果是()
public void add(Byte b){
b=b++;
}
public void test(){
Byte a=127;
Byte b=127;
add(++a);
System.out.print(a+" ");
add(b);
System.out.print(b+"");
}
++a后,a变成128,将128赋值给byte类型的变量后,回被当作是-128,故输出的结果是-128 127
二、编程题
2.1 二进制插入
2.1.1 题目
2.1.2 题解
思路:先让m左移j位,题目中说n的第i到j位都是0,因此再让m|n,得到的就是插入后的结果
代码:
public int binInsert(int n, int m, int j, int i) {
m<<=j;
return m|n;
}
2.2 查找组成一个偶数最接近的两个素数
2.2.1 题目
2.2.2 题解
思路:
因为题目要求找出的是最接近的两个素数,因此我们要从偶数/2的位置,开始寻找这两个偶数
代码:
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()){
int n=scanner.nextInt();
int half=n/2;
for(int i=half;i>0;i--){
if(isPrime(i)&& isPrime(n-i)){
System.out.println(i);
System.out.println(n-i);
break;
}
}
}
}
public static boolean isPrime(int n){
for(int i=2;i*i<=n;i++){
if(n%i==0){
return false;
}
}
return true;
}