文章目录 Java 基础 题目 1. 如下代码输出什么? 2. 当输入为2的时候返回值是多少? 3. 如下代码输出值为多少? 4. 给出一个排序好的数组:{1,2,2,3,4,5,6,7,8,9} 和一个数,求数组中连续元素的和等于所给数的子数组 解析 第一题 第二题 第三题 第四题 方案一:给定数为:10 方案二:即给定数字限定为:7
Java 基础
题目
1. 如下代码输出什么?
public classTest {
public void change ( String str, char [ ] ch) { str= "test ok" ; ch[ 0 ] = 'g' ;
} public static voidmain ( String [ ] args) { String str= new String ( "good" ) ; char [ ] ch = { 'a' , 'b' , 'c' } ; Test te= newTest ( ) ; te. change ( str, ch) ; System . out. print ( str+ "and" ) ; System . out. print ( ch) ; }
}
2. 当输入为2的时候返回值是多少?
public static int getValue ( int i) { int result = 0 ; switch ( i) { case 1 : result = result + i; case 2 : result = result + i * 2 ; case 3 : result = result + i * 3 ; } return result;
}
3. 如下代码输出值为多少?
public class Base
{ private String baseName = "base" ; public Base ( ) { callName ( ) ; } public void callName ( ) { System . out. println ( baseName) ; } static class Sub extends Base { private String baseName = "sub" ; public void callName ( ) { System . out. println ( baseName) ; } } public static void main ( String [ ] args) { Base b = new Sub ( ) ; }
}
4. 给出一个排序好的数组:{1,2,2,3,4,5,6,7,8,9} 和一个数,求数组中连续元素的和等于所给数的子数组
解析
第一题
答案:goodandgbc 这个题目很简单其主要细节在于输出语句: print,看清楚他是不换行的
第二题
答案:14 细节:没有 break ,所以他会继续执行下面的条件
第三题
答案:null 这一道题来自携程的笔试题,点击此处:答案解析
第四题
方案一:给定数为:10
使用两层循环必定可以解决这个问题,但是因为是两个数据求和,在集合有序的情况下使用一次循环就可以解决这个问题。 思路如下:因为数组有序这,可以让数组从两头开始向加
public static void main ( String [ ] args) { int [ ] num = { 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int sum = 10 ; int i = 0 ; int j = num. length - 1 ; while ( i < j) { if ( num[ i] + num[ j] > sum) { j -- ; } if ( num[ i] + num[ j] < sum) { i ++ ; } if ( num[ i] + num[ j] == sum) { System . out. println ( num[ i] + "---" + num[ j] ) ; } i ++ ; } }
方案二:即给定数字限定为:7
public static void main ( String [ ] args) { int [ ] num = { 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int sum = 7 ; findSum ( num, sum) ; } private static void findSum ( int [ ] num, int sum) { int left= 0 ; int right= 0 ; for ( int i= 0 ; i< num. length; i++ ) { int curSum = 0 ; left = i; right = i; while ( curSum< sum) { curSum += num[ right++ ] ; } if ( curSum== sum) { for ( int j= left; j< right; j++ ) { System . out. print ( num[ j] + " " ) ; } System . out. println ( ) ; } } }