JAVA数据结构习题及解答(英)
JAVA试题英文版(答案)
![JAVA试题英文版(答案)](https://img.taocdn.com/s3/m/5cb229459ec3d5bbfc0a743e.png)
一.Which two demonstrate an “is a” relationship? (Choose Two)A. public interface Person { }//语法错了public class Employee extends Person { }B. public interface Shape { }//语法错了public class Employee extends Sha pe { }C. public interface Color { }//语法错了public class Employee extends Color { }D. public class Species { }public class Animal{private Species species;}E. interface Component { }Class Container implements Component (Private Component[ ] children;二.which statement is true?A. An anonymous inner class may be declared as finalB. An anonymous inner class can be declared as privateC. An anonymous inner class can implement mutiple interfacesD. An anonymous inner class can access final variables in any enclosing scope (不能)E. Construction of an instance of a static inner class requires an instance of the encloing outer class构造一个静态的内部类对象需要构造包含它的外部类的对象三. Given:1. package foo;2.3. public class Outer (4.public static class Inner (5.)6. )Which statement is true?A. An instance of the Inner class can be constructed with “new Outer.Inner ()”B. An instance of the inner class cannot be constructed outside of package foo他们都是public的,只要在外部import就行C. An instance of the inner class can only be constructed from within the outerclassD. From within the package bar, an instance of the inner class can be constructed with “new inner()”四.Exhibit(展览、陈列):1 public class enclosinggone{2 public class insideone{}3 }4 public class inertest{5 public static void main (String[] args){6 enclosingone eo = new enclosingone();7 //insert code here8 }}Which statement at line 7 constructs an instance of the inner class?A. InsideOne ei = eo.new InsideOne(); 写程序试出来B. Eo.InsideOne ei = eo.new InsideOne();C InsideOne ei = EnclosingOne.new InsideOne();D.EnclosingOne InsideOne ei = eo.new InsideOne();五.1)interface Foo{2)int k=0;3)}4) public class Test implements Foo{5)public static void main(String args[]){6)int i;7) Test test =new Test();8)i=test.k;9)i=Test.k;10)i=Foo.k;11)}12) }What is the result?A. Compilation succeeds.B. An error at line 2 causes compilation to fail.C. An error at line 9 causes compilation to fail.D. An error at line 10 causes compilation to fail.E. An error at line 11 causes compilation to fail.六.//point Xpublic class Foo{public static void main(String[] args){PrintWriter out=new PrintWriter(newjava.io.OutputStreamWriter(System.out),true);out.println("Hello");}}which statement at point X on line 1 allows this code to compile and run?在point X这个位置要填入什么代码才能使程序运行A.import java.io.PrintWriterB.include java.io.PrintWriterC.import java.io.OutputStreamWriterD.include java.io.OutputStreamWriterE.No statement is needed本来两个都要import,但是后者OutputStreamWriter指定了包结构java.io.OutputStreamWriter七.what is reserved words in java? 保留字而非关键字A. runB.defaultC. implementD. import八. which three are valid declaraction of a float?(float作为整数是可以的,其余几个都是double)A. float foo=-1;B. float foo=1.0;C. float foo=42e1;D. float foo=2.02f;E. float foo=3.03d;F. float foo=0x0123;九.Given:8.int index = 1;9.boolean[] test = new boolean[3]; (数组作为对象缺省初始化为false)10. boolean foo= test [index];What is the result?A. foo has the value of 0B. foo has the value of nullC. foo has the value of trueD. foo has the value of falseE. an exception is thrownF. the code will not compile十. Given:1. public class test(2. public static void main(String[]args){3. String foo = args [1];4. String foo = args [2];5. String foo = args [3];6. }7. }And the command line invocation:Java TestWhat is the result?A. baz has the value of “”B. baz has the value of nullC. baz has the value of “red”D. baz has the value of “blue”E. bax has the value of “green”F. the code does not compileG. the program throws an exception(此题题目出错了,重复定义了变量foo,如果没有重复的话,应选G,因为只传递了0-2三个数组元素,而题目中需要访问args [3],所以会抛出数组越界异常)十一.int index=1;int foo[]=new int[3];int bar=foo[index]; //bar=0int baz=bar+index; //baz=1what is the result?A. baz has a value of 0B. baz has value of 1C. baz has value of 2D. an exception is thrownE. the code will not compile十二.1)public class Foo{2)public static void main(String args[]){3)String s;4)System.out.println("s="+s);5)}6)}what is the result?A. The code compiles and “s=” is printed.B. The code compiles and “s=null” is printed.C. The code does not compile because string s is not initialized.D. The code does not compile because string s cannot be referenced.E. The code compiles, but a NullPointerException is thrown when toString is called.十三. Which will declare a method that forces a subclass to implement it?(谁声明了一个方法,子类必须实现它)A. public double methoda();B. static void methoda (double d1) {}C. public native double methoda();D. abstract public void methoda();E. protected void methoda (double d1){}十四.You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access modifier that will accomplish this objective? (你希望子类在任何包里都能访问父类,为完成这个目的,下列哪个是最严格的访问权限)A. PublicB. PrivateC. ProtectedD. TransientE. No access modifier is qualified十五. Given:1. abstract class abstrctIt {2. abstract float getFloat ();3. )4. public class AbstractTest extends AbstractIt {5. private float f1= 1.0f;6. private float getFloat () {return f1;}7. }What is the result?A. Compilation is successful.B. An error on line 6 causes a runtime failure.(抛出实时异常)C. An error at line 6 causes compilation to fail.D. An error at line 2 causes compilation to fail.(子类覆盖父类方法的时候,不能比父类方法具有更严格的访问权限)十六. Click the exhibit button:1. public class test{2. public int aMethod(){3.static int i=0;4. i++;5. return I;6. }7. public static void main (String args[]){8. test test = new test();9. test.aMethod();10. int j = test.aMethod();11. System.out.printIn(j);12. }13. }(局部变量不能声明为静态)What is the result?A. Compilation will fail.B. Compilation will succeed and the program will print “0”.C. Compilation will succeed and the program will print “1”.D. Compilation will succeed and the program will print “2”.十七.1)class Super{2)public float getNum(){return 3.0f;}3)}4)5)public class Sub extends Super{6)7)}which method, placed at line 6, will cause a compiler error?A. public float getNum(){return 4.0f;}B. public void getNum(){} 返回值类型不同不足以构成方法的重载C. public void getNum(double d){}D. public double getNum(float d){return 4.0d;}十八. Which declaration prevents creating a subclass of an outer class?A.static class FooBar{}B.pivate class Foobar{}C.abstract class FooBar{}D.final public class FooBar{}E.final abstract class FooBar{} 抽象类不能声明为final十九. byte[] array1,array2[]byte array3[][]byte[][] array4if each has been initialized, which statement will cause a compile error?A. array2 = array1;B. array2 = array3;C. array2 = array4;D. both A and BE. both A and CF. both B and C(一维数组和二维数组的区别)二十.class Super{public int i=0;public Super(String text){i=1;}}public class Sub extends Super{public Sub(String text){i=2;}public static void main(String args[]){Sub sub=new Sub("Hello");System.out.println(sub.i);}}what is the result?A. compile will failB. compile success and print "0"C. compile success and print "1"D. compile success and print "2"子类总要去调用父类的构造函数,有两种调用方式,自动调用(无参构造函数),主动调用带参构造函数。
java数据结构期末考试题及答案
![java数据结构期末考试题及答案](https://img.taocdn.com/s3/m/3a476ea60d22590102020740be1e650e52eacffc.png)
java数据结构期末考试题及答案一、选择题(每题2分,共20分)1. 在Java中,哪个类提供了栈的实现?A. ArrayListB. LinkedListC. StackD. Vector答案:C2. 下列哪个选项是二叉树的遍历方式?A. 先序遍历B. 中序遍历C. 后序遍历D. 所有以上答案:D3. Java中HashMap的默认初始容量是多少?A. 10B. 16C. 32D. 64答案:B4. 在Java中,哪个接口定义了集合?A. CollectionB. IterableC. ListD. Set答案:A5. 下列哪个不是Java集合框架中的接口?A. ListB. SetC. MapD. Array答案:D6. Java中ArrayList和LinkedList的主要区别是什么?A. ArrayList基于动态数组实现,LinkedList基于链表实现B. ArrayList基于链表实现,LinkedList基于动态数组实现C. ArrayList和LinkedList都是基于链表实现D. ArrayList和LinkedList都是基于动态数组实现答案:A7. 在Java中,哪个类实现了优先队列?A. PriorityQueueB. QueueC. StackD. Deque答案:A8. Java中,哪个方法用于将数组转换为ArrayList?A. Arrays.asList()B. Collections.addAll()C. Arrays.copyOf()D. Collections.copy()答案:A9. 下列哪个不是Java集合框架中的类?A. HashSetB. TreeSetC. LinkedHashMapD. Object答案:D10. 在Java中,哪个类提供了双向队列的实现?A. QueueB. StackC. DequeD. List答案:C二、填空题(每题2分,共20分)1. Java中的______类实现了双端队列接口。
数据结构英文例题
![数据结构英文例题](https://img.taocdn.com/s3/m/233b160ab52acfc788ebc902.png)
I Single Choice(10 points)1. ( )For the following program fragment the running time(Big-Oh) is .i = 0;s = 0;while(s <( 5*n*n + 2)){ i++;s = s + i;}a. O(n)b. O(n2)c. O(n1/2)d. O(n3)2. ( )Which is non-linear data structure_____.a. queueb.stackc. treed. sequence list3.( )The worst-time for removing an element from a sequence list (Big-Oh) is .a. O(1)b. O(n)c. O(n2)d. O(n3)4.( )In a circular queue we can distinguish(区分) empty queues from full queues by .a. using a gap in the arrayb. incrementing queue positions by 2 instead of 1c.keeping a count of the number of elementsd. a and c5.( )A recursive function can cause an infinite sequence of function calls if .a.the problem size is halved at each stepb.the termination condition is missingc.no useful incremental computation is done in each stepd.the problem size is positive6.( )The full binary tree with height 4 has nodes.a. 15b. 16c.31d.327. ( )Searching in an unsorted list can be made faster by using .a.binary searchb. a sentinel(哨兵)at the end of the listc.linked list to store the elementsd. a and c8.()Suppose there are 3 edges in an undirected graph G, If we represent graph G with a adjacency matrix, How many “1”s are there in the matrix?a. 3b. 6c. 1d. 99. ( ) Construct a Huffman tree by four leaf whose weights are 9, 2, 5, 7 respectively. The weighted path length is___________.a. 29b. 37c. 46d.4410. Consider the following weighted graph.Consider Dijkstra’s algorithm on this graph t o find the shortest paths with s as a starting vertex. Which are the first four vertices extracted from the priority queue by the algorithm (listed in the order they are extracted) ?a. s, y, t, xb. s, y, x, zc. s, t, y, xd. s, y, x, tFig. 111. Here is an array of ten integers:5 3 8 9 1 7 0 26 4Suppose we partition this array using quicksort's partition function and using 5 for the pivot. Which shows the array after partition finishes:a. 5 3 4 2 1 0 7 9 6 8b. 0 3 4 2 1 5 7 9 6 8c. 3 1 0 2 4 5 8 9 6 7d. 3 1 0 2 4 5 8 9 7 6e. None of the aboveII Fill in Blank (10 points)1. For the following program fragment the running time(Big-Oh) is .for ( int i = 0; i < n; i++ )for ( int j = 0; j < =i; j++)s; //s为某种基本操作2. We store a 4×4 symmetric matrix A into an array B with row major order, Store the lower triangle only. the index of element a[2][3] in B is .3.We can use 3 vector type to store value and of non-zero elements in a sparse matrix.4. A______________ is a list where removal and addition occur at the same end . Frequently known a LIFO (Last-In-First-Out) structure.5.T( n ) = 2T( n/2 )+ cn, T(n) = T( n-1)+cn, T( n ) = O(___________)6. There is a binary tree whose elements are characters. Preorder list of the binary tree is “ABECDFGHIJ” and inorder list of the binary tree is “EBCDAFHIGJ”. Postorder traversal sequence of the binary tree is .7.There are leaf nodes in a full binary tree with n nodes.8.When the input has been sorted ,the running time of insertion sort(Big-Oh) is .9.We sort the sequence(43,02,80,48,26,57,15,73,21,24,66)with shell sort for increment 3, the result is ______ _ .10、In a circular queue, “front”and “rear”are the front pointer and rear pointer respectively. Queue size is “maxsize”. When insert an element in the queue, rear = _________11. A ____________________________________________ is an example of a search tree which is multiway (allows more than two children).12. A tree in which every node is no smaller than its children is termed______________________.III Application of Algorithms(35 points)1.Graph G shown in Fig 2 is a directed graph, please describe G with adjacency matrix and write the orders of breadth first traversal and depth first traversal.Fig.22.The sequence of input keys is shown below:19,1,23,14,55,20,84,27,68,11,10,17A fixed table size of 19 and a hash function H(key)=key%13,with linear probing(线性探测), fill the table below and compute the average length of successful search.3. Show the results of inserting 53,17,78,09,45,65,87 each , one at a time, in a initially empty max heap(大根堆)4. write the sequence of preorder,postorder traversals and add inorder threads in the tree.Fig. 35. Build a Huffman tree and determine Huffman code when the probability distribution(概率分布) over the 8 alphabets ( c1, c2, c3, c4, c5, c6, c7, c8 ) is (0.05, 0.25, 0.03, 0.06, 0.10, 0.11, 0.36, 0.046. Graph G shown in Fig 4 is a directed graph, please describe G with adjacency list and write topological ordering.Fig. 4IV Fill in blank of algorithms.(15)1.Here is single source shortest path algorithm Dijkstra. Fill in blank of the algorithm.class Graph { //图的类定义private:float Edge[NumVertices][NumVertices];float dist[NumVertices]; //最短路径长度数组int path[NumVertices]; //最短路径数组int S[NumVertices]; //最短路径顶点集public:void ShortestPath ( int, int );int choose ( int );};void Graph :: ShortestPath ( int n, int v ){//在具有n 个顶点的带权有向图中, 各边上权值由Edge[i][j]给出。
数据结构(Java版)习题解答
![数据结构(Java版)习题解答](https://img.taocdn.com/s3/m/2a7a1f1714791711cc79176c.png)
AI N D E X练习题答案第一章练习题答案(a) n+(n–1)+(n–2)+…+2+1=2)1(+ n n (b) n+(n–1)+(n–2)+…+2+1=2)1(+nnf(n)≦c.g(n) →f(n)=O(g(n))(a) f(n)=100n+9c=101, g(n)=n, n0=10得知f(n)=O(n)(b) f(n)=1000n2+100n–8c=2000, g(n)= n2, n0=1得知f(n)=O(n2)(c) f(n)=5*2n+9 n2+2c=10, n0=5得知f(n)=O(2n)f(n)≧c g(n) →f(n)=Ω(g(n)) (a) f(n)=3n+1c=2, n0=1, g(n)=n得知f(n)=Ω(n)(b) f(n)=100n2+4n+5c=10, n0=1, g(n)= n2得知f(n)=Ω(n2)(c) f(n)=8*2n+8n+16c=8, n0=1, g(n)= 2n得知f(n)=Ω(n2)c1.g(n)≦f(n)≦c2.g(n) →f(n)= Θ(g(n))(a) f(n)=3n+2c1=3, c2=6, n0=1得知f(n) = Θ (n)(b) f(n)=9n2+4n+2c1=9, c2=16, n0=1得知f(n) = Θ (n2)(c) f(n)=8n4+5n3+5c1=8, c2=20, n0=1得知f(n) = Θ (n4)A-2练习题解答第二章练习题答案1. 分别以行为主和以列为主说明之。
(a) 以行为主A(i, j)=l0+(i–1)*u2*d+(j–1)*d(b) 以列为主A(i, j)=l0+(j–1)*u1*d+(i–1)*d2. 以列为主A(i, j)=l0+(j–12)*md+(i–l1)dm=u1–l1+1=5–(–3)+1=9m=u2–l2+1=2–(–4)+1=7A(1, 1) =100+(1–(–4))*9+(1–(–3))=100+45+4=1493. 分别以行为主和以列为主的说明。
JAVA练习题含答案-answertopratice3
![JAVA练习题含答案-answertopratice3](https://img.taocdn.com/s3/m/0e4a4079ac02de80d4d8d15abe23482fb4da0278.png)
JAVA练习题含答案-answertopratice3Chapter 3Flow of ControlMultiple Choice1)An if selection statement executes if and only if:(a)the Boolean condition evaluates to false.(b)the Boolean condition evaluates to true.(c)the Boolean condition is short-circuited.(d)none of the above.Answer:B (see page 97)2) A compound statement is enclosed between:(a)[ ](b){ }(c)( )(d)< >Answer:B (see page 98)3) A multi-way if-else statement(a)allows you to choose one course of action.(b)always executes the else statement.(c)allows you to choose among alternative courses of action.(d)executes all Boolean conditions that evaluate to true.Answer:C (see page 100)4)The controlling expression for a switch statement includes all of the following types except:(a)char(b)int(c)byte(d)doubleAnswer:D (see page 104)Copyright ? 2006 Pearson Education Addison-Wesley. All rights reserved. 125)To compare two strings lexicographically the String method ____________ should be used.(a)equals(b)equalsIgnoreCase(c)compareTo(d)==Answer:C (see page 112)6)When using a compound Boolean expression joined by an && (AND) in an if statement:(a)Both expressions must evaluate to true for the statement to execute.(b)The first expression must evaluate to true and the second expression must evaluate to false forthe statement to execute.(c)The first expression must evaluate to false and the second expression must evaluate to true forthe statement to execute.(d)Both expressions must evaluate to false for the statement to execute.Answer:A (see page 116)7)The OR operator in Java is represented by:(a)!(b)&&(c)| |(d)None of the aboveAnswer:C (see page 116)8)The negation operator in Java is represented by:(a)!(b)&&(c)| |(d)None of the aboveAnswer:A (see page 116)9)The ____________ operator has the highest precedence.(a)*(b)dot(c)+=(d)decrementAnswer:B (see page 123)10)The looping mechanism that always executes at least once is the _____________ statement.(a)if…else(b)do…while(c)while(d)forAnswer:B (see page 132).Chapter 3 Flow of Control 311) A mixture of programming language and human language is known as:(a)Algorithms(b)Recipes(c)Directions(d)PseudocodeAnswer:D (see page 134)12)When the number of repetitions are known in advance, you should use a ___________ statement.(a)while(b)do…while(c)for(d)None of the aboveAnswer:C (see page 141)13)To terminate a program, use the Java statement:(a)System.quit(0);(b)System.end(0);(c)System.abort(0);(d)System.exit(0);Answer:D (see page 148)True/False1)An if-else statement chooses between two alternative statements based on the value of a Booleanexpression.Answer:True (see page 96)2)You may omit the else part of an if-else statement if no alternative action is required.Answer:True (see page 97)3)In a switch statement, the choice of which branch to execute is determined by an expression given inparentheses after the keyword switch.Answer:True (see page 104)4)In a switch statement, the default case is always executed.Answer:False (see page 104)5)Not including the break statements within a switch statement results in a syntax error.Answer:False (see page 104)6)The equality operator (==) may be used to test if two string objects contain the same value.Answer:False (see page 111)47)Boolean expressions are used to control branch and loop statements.Answer:True (see page 116)8)The for statement, do…while statement and while statement are examples of branching mechanisms.Answer:False (see page 130)9)An algorithm is a step-by-step method of solution.Answer:True (see page 134)10)The three expressions at the start of a for statement are separated by two commas.Answer:False (see page 137)Short Answer/Essay1)What output will be produced by the following code?public class SelectionStatements{public static void main(String[] args){int number = 24;if(number % 2 == 0)System.out.print("The condition evaluated to true!");elseSystem.out.print("The condition evaluated to false!");}}Answer:The condition evaluated to true!.Chapter 3 Flow of Control 52)What would be the output of the code in #1 if number was originally initialized to 25?Answer:The condition evaluated to false!3)Write a multi-way if-else statement that evaluates a persons weight on the following criteria: Aweight less than 115 pounds, output: Eat 5 banana splits! A weight between 116 pounds and 130 pounds, output: Eat a banana split! A weight between 131 pounds and 200 pounds, output: Perfect!A weight greater than 200 pounds, output: Plenty of banana splits have been consumed!Answer:if(weight <= 115)System.out.println("Eat 5 banana splits!");else if(weight <= 130)System.out.println("Eat a banana split!");else if(weight <=200)System.out.println("Perfect!");elseSystem.out.println("Plenty of banana splits have been consumed!");4)Write an if-else statement to compute the amount of shipping due on an online sale. If the cost ofthe purchase is less than $20, the shipping cost is $5.99. If the cost of the purchase over $20 and at most $65, the shipping cost is $10.99. If the cost of the purchase is over $65, the shipping cost is $15.99.Answer:if(costOfPurchase < 20)shippingCost = 5.99;else if((costOfPurchase > 20)&&(costOfPurchase <= 65))shippingCost = 10.99;elseshippingCost = 15.99;5)Evaluate the Boolean equation: !( ( 6 < 5) && (4 < 3))Answer:True66)Write Java code that uses a do…while loop that prints even numbers from 2 through 10.Answer:int evenNumber = 2;do{System.out.println(evenNumber);evenNumber += 2;}while(evenNumber <= 10);7)Write Java code that uses a while loop to print even numbers from 2 through 10.Answer:int evenNumber = 2;while(evenNumber <= 10){System.out.println(evenNumber);evenNumber += 2;}Answer:8)Write Java code that uses a for statement to sum the numbers from 1 through 50. Display the totalsum to the console.Answer:.Chapter 3 Flow of Control 7 int sum = 0;for(int i=1; i <= 50; i++){sum += i;}System.out.println("The total is: " + sum);9)What is the output of the following code segment?public static void main(String[] args){int x = 5;System.out.println("The value of x is:" + x);while(x > 0){x++;}System.out.println("The value of x is:" + x);}Answer:.10)Discuss the differences between the break and the continue statements when used in loopingmechanisms.Answer:When the break statement is encountered within a looping mechanism, the loopimmediately terminates. When the continue statement is encountered within a looping mechanism, the current iteration is terminated, and execution continues with the next iteration of the loop.8Programming projects:1. Write a complete Java program that prompts the user fora series of numbers to determine the smallestvalue entered. Before the program terminates, display the smallest value.Answer:import java.util.Scanner;public class FindMin{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);int smallest = 9999999;String userInput;boolean quit = false;System.out.println("This program finds the smallest number"+ " in a series of numbers");System.out.println("When you want to exit, type Q");.Chapter 3 Flow of Control 9 while(quit != true){System.out.print("Enter a number: ");userInput = keyboard.next();if(userInput.equals("Q") || userInput.equals("q")){quit = true;}else{int userNumber = Integer.parseInt(userInput);if(userNumber < smallest)smallest = userNumber;}}System.out.println("The smallest number is " + smallest);System.exit(0);}10}2. Write a complete Java program that uses a for loop to compute the sum of the even numbers and thesum of the odd numbers between 1 and 25.public class sumEvenOdd{public static void main(String[] args){int evenSum = 0;int oddSum = 0;//loop through the numbersfor(int i=1; i <= 25; i++){if(i % 2 == 0){//even numberevenSum += i;}else{oddSum += i;.Chapter 3 Flow of Control 11 }}//Output the resultsSystem.out.println("Even sum = " + evenSum);System.out.println("Odd sum = " + oddSum);}}/*** Question2.java** This program simulates 10,000 games of craps.* It counts the number of wins and losses and outputs the probability* of winning.** Created: Sat Mar 05, 2005** @author Kenrick Mock* @version 1*/public class Question2{private static final int NUM_GAMES = 10000;/*** This is the main method. It loops 10,000 times, each simulate* a game of craps. Math.random() is used to get a random number,* and we simulate rolling two dice (Math.random() * 6 + 1 simulates* a single die).*/public static void main(String[] args){// Variable declarationsint numWins = 0;12int numLosses = 0;int i;int roll;int point;// Play 10,000 gamesfor (i=0; i<="" p="">{// Simulate rolling the two dice, with values from 1-6roll = (int) (Math.random() * 6) + (int) (Math.random() * 6) + 2;// Check for initial win or lossif ((roll == 7) || (roll == 11)){numWins++;}else if ((roll==2) || (roll==3) || (roll==12)){numLosses++;}else{// Continue rolling until we get the point or 7point = roll;do{roll = (int) (Math.random() * 6) + (int) (Math.random() * 6) +2;if (roll==7){numLosses++;}else if (roll==point){numWins++;}} while ((point != roll) && (roll != 7));}}// Output probability of winningSystem.out.println("In the simulation, we won " + numWins +" times and lost " + numLosses + " times, " +" for a probability of " +(double) (numWins) / (numWins+numLosses));}} // Question2.Chapter 3 Flow of Control 13 /*** Question6.java** Created: Sun Nov 09 16:14:44 2003* Modified: Sat Mar 05 2005, Kenrick Mock** @author Adrienne Decker* @version 2*/import java.util.Scanner;public class Question6{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);while ( true ){System.out.println("Enter the initial size of the green crud" + " in pounds.\nIf you don't want to " +"calculate any more enter -1.");int initialSize = keyboard.nextInt();if ( initialSize == -1){break;} // end of if ()System.out.println("Enter the number of days: ");int numDays = keyboard.nextInt();int numOfRepCycles = numDays / 5;int prevPrevGen = 0;int prevGen = initialSize;int finalAnswer = initialSize;for ( int i = 0; i < numOfRepCycles; i++ ){finalAnswer = prevPrevGen + prevGen;14prevPrevGen = prevGen;prevGen = finalAnswer;} // end of for ()System.out.println("The final amount of green crud will be: "+ finalAnswer + " pounds.\n");} // end of while ()}} // Question6/*** Question7.java** Created: Sun Nov 09 16:14:44 2003* Modified: Sat Mar 05 2005, Kenrick Mock** @author Adrienne Decker* @version 2*/import java.util.Scanner;public class Question7{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);String line;do{System.out.println("Enter the value of X for this calculation."); double x = keyboard.nextDouble();double sum = 1.0;double temp = 1.0;for ( int n = 1; n <= 10; n++){System.out.print("For n equal to: " + n.Chapter 3 Flow of Control 15+ ", the result of calculating e^x is: ");for ( int inner = 1; inner <= n; inner++){temp = 1.0;for ( double z = inner; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);sum = 1.0;} // end of for ()System.out.print("For n equal to 50, the result of " + "calculating e^x is: ");for ( int n = 1; n <= 50; n++){temp = 1.0;for ( double z = n; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);sum = 1;System.out.print("For n equal to 100, the result of " + "calculating e^x is: ");for ( int n = 1; n <= 100; n++){temp = 1.0;for ( double z = n; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);System.out.println("\nEnter Q to quit or Y to go again.");16keyboard.nextLine(); // Clear bufferline = keyboard.nextLine();} while (line.charAt(0)!='q' && line.charAt(0)!='Q'); // end of while () }} // Question7.。
java考试选择题英文版
![java考试选择题英文版](https://img.taocdn.com/s3/m/320b1f4d793e0912a21614791711cc7931b7781a.png)
java考试选择题英文版Read the questions carefullyI have tried to make the questions unambiguous (the meaning should be obvious), but make sure you have read what I have written not what you think I might have written. Thus if it says "Classes can be declared with the private modifier ", it means It is possible to declare a class with the private modifier and not that all classes in all situations can be declared as private. Each question may have one or more correct Answers.QuestionsQuestion 1)Which of the following lines will compile without warning or error.1) float f=1.3;2) char c="a";3) byte b=257;4) boolean b=null;5) int i=10;Question 2)What will happen if you try to compile and run the following codepublic class MyClass {public static void main(String arguments[]) {amethod(arguments);}public void amethod(String[] arguments) {System.out.println(arguments);System.out.println(arguments[1]);}}1) error Can't make static reference to void amethod.2) error method main not correct3) error array must include parameter4) amethod must be declared with StringBecause main is defined as static you need to create an instance of the class in order to call any non-static methods.--------------------------------------------------------------------------------Question 3)Which of the following will compile without error要先出现package1) import java.awt.*;package Mypackage;class Myclass {}2) package MyPackage;import java.awt.*;class MyClass{}3) /*This is a comment */package MyPackage;import java.awt.*;class MyClass{}--------------------------------------------------------------------------------Question 4)A byte can be of what size1) -128 to 1272) (-2 power 8 )-1 to 2 power 83) -255 to 2564)depends on the particular implementation of the JavaVirtual machine--------------------------------------------------------------------------------Question 5)What will be printed out if this code is run with the following command line?Java myprog good morning;public class myprog{public static void main(String argv[]){System.out.println(argv[2]);}}1) myprog2) good3) morning4) Exception raised: "/doc/8d6822986.html,ng.ArrayIndexOutOfBou ndsException: 2" --------------------------------------------------------------------------------Question 6)Which of the following are keywords or reserved (预定义)words in Java?1) if2) then3) goto4) while5) case--------------------------------------------------------------------------------Question 7)Which of the following are legal identifiers(标识符)1) 2variable2) variable23) _whatavariable4) _3_5) $anothervar6) #myvar--------------------------------------------------------------------------------Question 8)What will happen when you compile and run the following code?public class MyClass{static int i;public static void main(String argv[]){System.out.println(i);}}局部变量(在函数内部)必须先初始化,类级别的可以不初始化Class level variables are always initialised to default values. In the case of an int this will be 0. Method level variables are not given default values and if you attempt to use one before it has been initialised it will cause theError Variable i may not have been initialized1) Error Variable i may not have been initialized2) null3) 14) 0--------------------------------------------------------------------------------Question 9)What will happen if you try to compile and run the following code?public class Q {public static void main(String argv[]){int anar[]=new int[]{1,2,3};System.out.println(anar[1]);}}1) 12) Error anar is referenced before it is initialized3) 24) Error: size of array must be defined-------------------------------------------------------------------------------- Question 10)What will happen if you try to compile and run the following code?public class Q {public static void main(String argv[]){int anar[]=new int[5];System.out.println(anar[0]);}}1) Error: anar is referenced before it is initialized2) null3) 04) 5-------------------------------------------------------------------------------- Question 11)What will be the result of attempting to compile and run the following code?abstract class MineBase {abstract void amethod();static int i;}public class Mine extends MineBase {public static void main(String argv[]){int[] ar=new int[5];for(i=0;i < ar.length;i++)System.out.println(ar[i]);}}Any class derived from an abstract class must either define all of the abstract methods or be declared abstract itself.1) a sequence of 5 0's will be printed2) Error: ar is used before it is initialized3) Error Mine must be declared abstract4) IndexOutOfBoundes Error--------------------------------------------------------------------------------Question 12)What will be printed out if you attempt to compile and run the following code ?int i=1;switch (i) {case 0: System.out.println("zero");break;case 1: System.out.println("one");case 2: System.out.println("two");default: System.out.println("default");}1) one2) one, default3) one, two, default4) default--------------------------------------------------------------------------------Question 13)What will be printed out if you attempt to compile and run the following code?int i=9;switch (i) {default: System.out.println("default");case 0: System.out.println("zero");break;case 1: System.out.println("one");case 2: System.out.println("two");}1) default2) default, zero3) error default clause not defined4) no output displayed--------------------------------------------------------------------------------Question 14)Which of the following lines of code will compile without error1) int i=0;if(i) {System.out.println("Hello");}2) boolean b=true;boolean b2=true;if(b==b2) {System.out.println("So true");}3) int i=1;int j=2;if(i==1|| j==2) System.out.println("OK");4) int i=1;int j=2;if(i==1 &| j==2) System.out.println("OK");--------------------------------------------------------------------------------Question 15)What will be output if you try to compile and run the following code, but there is no file called Hello.txt in the current directory?.import java.io.*;public class Mine {public static void main(String argv[]){Mine m=new Mine();System.out.println(m.amethod());}public int amethod() {try {FileInputStream dis=new FileInputStream("Hello.txt");}catch (FileNotFoundException fne) {System.out.println("No such file found");return -1;}catch(IOException ioe) { }finally{System.out.println("Doing finally");}return 0;}}1) No such file found2 No such file found ,-13) No such file found, Doing finally, -14) 0--------------------------------------------------------------------------------Question 16)Which of the following statements are true?1) Methods cannot be overriden to be more private2) static methods cannot be overloadedStatic methods cannot be overriden but they can be overloaded3) private methods cannot be overloaded4) An overloaded method cannot throw exceptions not checked in the base class--------------------------------------------------------------------------------Question 17)What will happen if you attempt to compile and run the following code?class Base {}class Sub extends Base {}class Sub2 extends Base {}public class CEx{public static void main(String argv[]){Base b=new Base();Sub s=(Sub) b;}}1) Compile and run without error2) Compile time Exception3) Runtime Exception--------------------------------------------------------------------------------Question 18)Which of the following statements are true?1) System.out.println( -1 >>> 2);will output a result larger than 10 无符号右移2) System.out.println( -1 >> 2); will output a positive number 输出-13) System.out.println( 2 >> 1); will output the number 14) System.out.println( 1 <<< 2); will output the number 4--------------------------------------------------------------------------------Question 19)What will happen when you attempt to compile and run the following code?public class Tux extends Thread{static String sName = "vandeleur";public static void main(String argv[]){Tux t = new Tux();t.piggy(sName);System.out.println(sName);}public void piggy(String sName){sName = sName + " wiggy";start();}public void run(){for(int i=0;i < 4; i++){sName = sName + " " + i;}}}1) Compile time error2) Compilation and output of "vandeleur wiggy"3) Compilation and output of "vandeleur wiggy 0 1 2 3"4) Compilation and output of either "vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"--------------------------------------------------------------------------------Question 20)What will be displayed when you attempt to compile and run the following code//Code startimport java.awt.*;public class Butt extends Frame{public static void main(String argv[]){Butt MyBut=new Butt();}Butt(){Button HelloBut=new Button("Hello");Button ByeBut=new Button("Bye");add(HelloBut);add(ByeBut);setSize(300,300);setVisible(true); }}//Code end1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on the right2) One button occupying the entire frame saying Hello3) One button occupying the entire frame saying Bye4) Two buttons at the top of the frame one saying Hello the other saying Bye--------------------------------------------------------------------------------Question 21)What will be output by the following code?public class MyFor{public static void main(String argv[]){int i;int j;outer: for (i=1;i <3;i++)inner: for(j=1; j<3; j++) {if (j==2) continue outer;System.out.println("Value for i=" + i + " Value for j=" +j);}}}1) Value for i=1 Value for j=12) Value for i=2 Value for j=13) Value for i=2 Value for j=24) Value for i=3 Value for j=1--------------------------------------------------------------------------------Question 22)Which statement is true of the following code?public class Agg{public static void main(String argv[]){Agg a = new Agg();a.go();}public void go(){DSRoss ds1 = new DSRoss("one");ds1.start();}}class DSRoss extends Thread{private String sTname="";DSRoss(String s){sTname = s;}public void run(){notwait();System.out.println("finished");}public void notwait(){while(true){try{System.out.println("waiting");wait();}catch(InterruptedException ie){}System.out.println(sTname);notifyAll();}} }1) It will cause a compile time error2) Compilation and output of "waiting"3) Compilation and output of "waiting" followed by "finished"4) Runtime error, an exception will be thrown--------------------------------------------------------------------------------Question 23)Which of the following methods can be legally inserted in place of the comment //Method Here ?class Base{public void amethod(int i) { }}public class Scope extends Base{public static void main(String argv[]){ }//Method Here}1) void amethod(int i) throws Exception {}2) void amethod(long i)throws Exception {}3) void amethod(long i){}4) public void amethod(int i) throws Exception {}--------------------------------------------------------------------------------Question 24)Which of the following will output -4.01) System.out.println(Math.floor(-4.7));2) System.out.println(Math.round(-4.7));3) System.out.println(Math.ceil(-4.7));4) System.out.println(Math.min(-4.7));Options 1 and 2 will produce -5 and option 4 will not compile because the min method requires 2 parameters.--------------------------------------------------------------------------------Question 25)What will happen if you attempt to compile and run the following code?Integer ten=new Integer(10);Long nine=new Long (9);System.out.println(ten + nine);int i=1;System.out.println(i + ten);1) 19 followed by 202) 19 followed by 113) Compile time error4) 10 followed by 1--------------------------------------------------------------------------------Question 26)If you run the code below, what gets printed out?String s=new String("Bicycle");int iBegin=1;char iEnd=3;System.out.println(s.substring(iBegin,iEnd));1) Bic2) ic3) icy4) error: no method matching substring(int,char)--------------------------------------------------------------------------------Question 27)If you wanted to find out where the position of the letter v (ie return 2) in the string s containing "Java", which of the following could you use?1) mid(2,s);2) charAt(2);3) s.indexOf('v');4) indexOf(s,'v');--------------------------------------------------------------------------------Question 28)Given the following declarationsString s1=new String("Hello");String s2=new String("there");String s3=new String();Which of the following are legal operations?1) s3=s1 + s2;2) s3=s1-s2;3) s3=s1 & s2;4) s3=s1 && s2--------------------------------------------------------------------------------Question 29)What is the result of the following operation?System.out.println(4 | 3); 1000111111) 62) 03) 14) 7--------------------------------------------------------------------------------Question 30)public class MyClass1 {public static void main(String argv[]){ }/*Modifier at XX */class MyInner {}}What modifiers would be legal at XX in the above code?1) public2) private3) static4) friend-------------------------------------------------------------------------------- Question 31)What will happen when you attempt to compile and run the following code?public class Holt extends Thread{private String sThreadName;public static void main(String argv[]){Holt h = new Holt();h.go();}Holt(){}Holt(String s){sThreadName = s;}public String getThreadName(){return sThreadName;}public void go(){Holt first = new Holt("first");first.start();Holt second = new Holt("second");second.start();}public void start(){for(int i = 0; i < 2; i ++){System.out.println(getThreadName()+i);try{Thread.sleep(100);}catch(InterruptedExceptione){System.out.println(e.getMessage());} } }}1) Compile time error2) Output of first0, second0, first0, second13) Output of first0, first1, second0, second14) Runtime error--------------------------------------------------------------------------------Question 32)An Applet has its Layout Manager set to the default of FlowLayout. What code would be correct to change to another Layout Manager.1) setLayoutManager(new GridLayout());2) setLayout(new GridLayout(2,2));3) setGridLayout(2,2);4) setBorderLayout();--------------------------------------------------------------------------------Question 33)What will happen when you attempt to compile and run thefollowing code?.class Background implements Runnable{int i=0;public int r un(){while(true){i++;System.out.println("i="+i);} //End whilereturn 1;}//End run}//End class1) It will compile and the run method will print out the increasing value of i.2) It will compile and calling start will print out the increasing value of i.3) The code will cause an error at compile time.4) Compilation will cause an error because while cannot takea parameter of true.--------------------------------------------------------------------------------Question 34)Which of the following statements about this code are true?public class Morecombe{public static void main(String argv[]){Morecombe m = new Morecombe();m.go(new Turing(){});}public void go(Turing t){t.start();}}class Turing extends Thread{public void run(){for(int i =0; i < 2; i++){System.out.println(i); }}}1) Compilation error due to malformed parameter to go method2) Compilation error, class Turing has no start method3) Compilation and output of 0 followed by 14) Compilation but runtime error--------------------------------------------------------------------------------Question 35)What will be the result when you attempt to compile and run the following code?.public class Conv{public static void main(String argv[]){Conv c=new Conv();String s=new String("ello");c.amethod(s);}public void amethod(String s){char c='H';c+=s;System.out.println(c);}}1) Compilation and output the string "Hello"2) Compilation and output the string "ello"3) Compilation and output the string elloH4) Compile time error--------------------------------------------------------------------------------Question 36)Given the following code, what test would you need to put in place of the comment line? //place test hereto result in an output of the string Equalpublic class EqTest{public static void main(String argv[]){EqTest e=new EqT est();}EqTest(){String s="Java";String s2="java";//place test here {System.out.println("Equal");}else{System.out.println("Not equal");}}}1) if(s==s2)2) if(s.equals(s2)3) if(s.equalsIgnoreCase(s2))4)if(s.noCaseMatch(s2))--------------------------------------------------------------------------------Question 37)Given the following codeimport java.awt.*;public class SetF extends Frame{public static void main(String argv[]){SetF s=new SetF();s.setSize(300,200);s.setVisible(true);}}How could you set the frame surface color to pink1)s.setBackground(Color.pink);2)s.setColor(PINK);3)s.Background(pink);4)s.color=Color.pink--------------------------------------------------------------------------------Question 38)How can you change the current working directory using an instance of the File class called FileName?1) FileName.chdir("DirName")2) FileName.cd("DirName")3) FileName.cwd("DirName")4) The File class does not support directly changing the current directory.--------------------------------------------------------------------------------Question 39)If you create a TextField with a constructor to set it to occupy 5 columns, what difference will it make if you use it with a proportional font (ie Times Roman) or a fixed pitch typewriterstyle font (Courier).1)With a fixed font you will see 5 characters, with a proportional it will depend on the width of the characters2)With a fixed font you will see 5 characters,with a proportional it will cause the field to expand to fit the text3)The columns setting does not affect the number of characters displayed4)Both will show exactly 5 characters--------------------------------------------------------------------------------Question 40)Given the following code how could you invoke the Base constructor that will print out the string "base constructor";class Base{Base(int i){System.out.println("base constructor"); }Base(){ }}public class Sup extends Base{public static void main(String argv[]){Sup s= new Sup();//One }Sup() { //Two }public void derived() { //Three }}1) On the line After //One put Base(10);2) On the line After //One put super(10);3) On the line After //Two put super(10);4) On the line After //Three put super(10);--------------------------------------------------------------------------------Question 41)Given the following code what will be output?public class Pass{ static int j=20;public static void main(String argv[]){ int i=10; Pass p = new Pass(); p.amethod(i);System.out.println(i); System.out.println(j); }public void amethod(int x){ x=x*2; j=j*2; }}1) Error: amethod parameter does not match variable2) 20 and 403) 10 and 404) 10, and 20--------------------------------------------------------------------------------Question 42)What code placed after the comment //For loop would result in the population of every element of the array ia[] with a value from variable i.?public class Lin{ public static void main(String argv[]){ Lin l = new Lin(); l.amethod(); }public void amethod(){ int ia[] = new int[4]; //Start For loop{ ia[i]=i; System.out.println(ia[i]);}}}1) for(int i=0; i < ia.length() -1; i++)2) for (int i=0; i< ia.length(); i++)3) for(int i=1; i < 4; i++)4) for(int i=0; i< ia.length;i++)--------------------------------------------------------------------------------Question 43)What will be the result when you try to compile and run the following code?private class Base{Base(){int i = 100;System.out.println(i);}}public class Pri extends Base{static int i = 200;public static void main(String argv[]){Pri p = new Pri();System.out.println(i);}}1) Error at compile time2) 2003) 100 followed by 2004) 100--------------------------------------------------------------------------------Question 44)What will the following code print out?public class Oct{public static void main(String argv[]){ Oct o = new Oct(); o.amethod(); }public void amethod(){int oi= 012; System.out.println(oi);}}1)122)0123)10 8*1 + 8^0 * 2 = 104)10.0--------------------------------------------------------------------------------Question 45)You need to create a class that will store unique object elements. You do not need to sort these elements but they must be unique.What interface might be most suitable to meet this need?。
数据结构样卷3(英文)
![数据结构样卷3(英文)](https://img.taocdn.com/s3/m/7550d30d763231126edb11a6.png)
重庆大学 《数据结构》 课程样卷 3开课学院: 计算机学院 课程号: 18001035 考试日期:考试方式:考试时间: 120 分钟一、 Single choice1. Merge two ordered list, both of them contain n elements, the least timesof comparison is ( ).A. nB. 2n-1C. 2nD. n-12. Sequential stored linear list with the length of 1000, if we insertan element into any position, the possibility is equal, when we insert a new element, the average number of removing elements is ( ). A. 1000 B. 1001 C. 500 D. 4993. Assume that the initial status of stack S and queue Q are both NULL,push elements e1,e2,e3,e4,e5,e6 into the stack S one by one, an element pops from stack, then enter into queue Q. If the sequence which the six elements in the dequeue is e2,e4,e6,e5,e3,e1, the capacity of stack S is at least ( ).A. 6B. 4C. 3D. 24. Two-dimensional array A [10 .. 20,5 .. 10] stores in line sequence,each element occupies 4 storage location, and the memory address of A[10,5] is 1000, then the address of A[20,9] is ( ). A. 1212 B. 1256 C. 1368 D. 13645. A tree with degree 3, it has 2 nodes with the degree 3, one node withthe degree 2, and 2 nodes with the degree 1, so the number of nodes with degree 0 is ( ).A. 4.B. 5.C. 6.D. 76. The inorder sequence of a binary tree is ABCDEFG, and its postordersequence is BDCAFGE, so its pre-order sequence is ( ) A. EGFACDB B. EACBDGF C. EAGCFBD D. EGAFCDB7. A Huffman tree with n leaf nodes, its total number of nodes is ( )A. n-1B. n+1C. 2n-1D. 2n+18. In an adjacency list of undirected graph with n vertexes and e edges,the number of edge node is ( ).A. nB. neC. eD. 2e9. The degree (sum of in-degree and out-degree) of a directed graph isk1, and the number of out-degree is k2. Therefore, in its adjacency list, the number of edge nodes in this singly linked list is ( ). A. k1 B. k2 C. k1-k2 D. k1+k210. If the graph has n vertexes is a circle, so it has ( ) spanning tree.A. nB. 2nC. n-1D.n+111. When look up a sequential list with the length 3, the possibility thatwe find the first element is 1/2, and the possibility that we find the second element is 1/3, the possibility that we find the third element is 1/6, so the average searching length to search any element (find it successfully and the sentry is at the end of the list) is ( ) A. 5/3 B.2 C. 7/3 D.4/312. There is an ordered list {3,5,7,8,11,15,17,22,23,27,29,33}, by binarysearch to search 27, so the number of comparison is ( ) A. 2 B. 3 C. 4 D. 513. Sort the following keyword sequences by using Quicksort, and theslowest one is ( )A. 19,23,3,15,7,21,28B. 23,21,28,15,19,3,7C. 19,7,15,28,23,21,3D. 3,7,15,19,21,23,28 14. Heapsort needs additional storage complexity is ( )A. O(n)B. O(nlog 2n)C. O(n 2) D. O(1)15. If we sort an array within the time complexity of O(nlog2n), needingsort it stably, the way that we can choose is ( )A. Merge sortB. Direct insertion sortC. Heap sortD. Quicksort二、 Fill the blanks1.Assume that the structure of the nodes in doubly circular linked list is (data,llink,rlink), without a head node in the list, if we want命题人:组题人:审题人:命题时间: 教务处制学院 专业、班 年级 学号 姓名公平竞争、诚实守信、严肃考纪、拒绝作弊封线密to insert the node which pointer s points after the node pointer ppoints, then execute as the following statements:; ; ___ _; ;2.Both stack and queue are _______linear structure.3.The four leaf nodes with the weight 9,2,5,7 form a Huffman tree, itsweighted path length is ________.4.In order to ensure that an undirected graph with six vertexes isconnected, need at least ______ edges.5.An n-vertex directed graph, if the sum of all vertices’ out-degreeis s, then the sum of all vertices’ degree is__ ___.6.The Depth-First traversal of a graph is similar to the binarytree_______ traversal; the Breadth-first graph traversal algorithmis similar to the binary tree ______traversal.7. A connected graph with n vertexes and e edges has ____ edges of itsspanning tree.8.The time complexity of binary searching is _____; if there are 100elements, the maximum number of comparisons by binary searching is____.9.Sort n elements by merge sort, the requiring auxiliary space is _____.10.Sort a linear list with 8 elements by Quicksort, at the best, thecomparison time is ______.三、 Application1. Begin from the vertex A, seek the minimum spanning tree by using Primalgorithms2. The following is AOE network:(1) How much time does it take to complete the whole project?(2) Find out all of the critical path.(9 points)3. Assume that a set of keywords is {1,12,5,8,3,10,7,13,97},tryto complete the following questions:(9 points)(1) Choose the keywords in sequence to build a binary sort tree Bt;(2) Draw the structure of the tree after deleting node “12”from thebinary tree Bt.4. The keyword sequence is {503,87,512,61,908,170,897,275,653,462}, usingradix sorting method to sort them in ascending order, try to write every trip results of sort. (9 points)四、 Algorithm1.The following algorithm execute on a singly linked list without headnode, try to analyze and write its function.(5 points)void function(LinkNode *head){LinkNode *p,*q,*r;p=head;q=p->next;while(q!=NULL){r=q->next;q->next=p;p=q;q=r;}head->next=NULL;head=p;}2.Design an algorithm to divide a singly linked list ‘A’ with a headpointer ‘a’ into two singly linked list ‘A’ and ‘B’, whose head pointers are ‘a’and ‘b’, respectively. On the condition that linked list A has all elements of odd serial number in the previous linked listA and linked listB has all elements of even serial number in the previouslinked list A, in addition, the relative order of the original linked list are maintained.(7 points)3. The type of binary tree is defined as follows:typedef struct BiTNode {char data;struct BiTNode *lchild,*rchild;}BiTNode, *BiTree;Please design an algorithm to count how many leaf nodes the binary tree have. (8 points)。
java英语笔试试题及答案
![java英语笔试试题及答案](https://img.taocdn.com/s3/m/18e4d99c59f5f61fb7360b4c2e3f5727a5e92438.png)
java英语笔试试题及答案Java英语笔试试题及答案1. What is the difference between a class and an object in Java?A class is a blueprint or template that defines the properties and methods of an object. An object is an instance of a class, created at runtime.2. What is the purpose of the 'public static voidmain(String[] args)' method in Java?The 'public static void main(String[] args)' method is the entry point of a Java application. It is the first methodthat gets executed when the program starts.3. What is the difference between a method and a function in Java?In Java, a method is a block of code that is used to perform a specific task. A function is a term that is often used interchangeably with method, but technically, a function can return a value whereas a method does not necessarily do so.4. What is the 'this' keyword used for in Java?The 'this' keyword in Java is a reference to the current object. It can be used to access instance variables and methods of the current object.5. What is an interface in Java?An interface in Java is a completely abstract class that can contain only abstract methods and constants. It is used to achieve abstraction and to define a contract for classes to implement.6. What is the difference between a checked exception and an unchecked exception in Java?A checked exception is a type of exception that a method must either handle with a try-catch block or declare it with the 'throws' keyword. An unchecked exception is not required to be handled or declared, and includes RuntimeException and its subclasses.7. What is the 'final' keyword used for in Java?The 'final' keyword in Java can be used in three different contexts: to declare a class as final (cannot be subclassed), to declare a method as final (cannot be overridden), or to declare a variable as final (cannot be reassigned).8. What is a constructor in Java?A constructor in Java is a special method that is used to initialize objects. It has the same name as the class and is called when an object is created.9. What is the purpose of the 'super' keyword in Java?The 'super' keyword in Java is used to refer to the parent class's methods and variables. It is often used in constructors to call a superclass's constructor.10. What is the difference b etween '==’ and 'equals()' inJava?The '==' operator is used to compare primitive data types by value and object references by reference, whereas the'equals()' method is used to compare objects by content, and it can be overridden to provide custom comparison logic.Answers:1. A class is a blueprint, an object is an instance of a class.2. It is the entry point of a Java application.3. A method is a block of code in Java, a function is a more general term and can return a value.4. It refers to the current object.5. An interface is an abstract class with only abstract methods and constants.6. Checked exceptions must be handled or declared, unchecked do not.7. It is used to declare classes, methods, or variables as final.8. It initializes objects.9. It refers to the parent class's methods and variables.10. '==' compares by value or reference, 'equals()' compares by content.。
java基础试题及答案英文
![java基础试题及答案英文](https://img.taocdn.com/s3/m/5f503498f605cc1755270722192e453610665bb9.png)
java基础试题及答案英文1. What is Java?Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.2. What are the main features of Java?The main features of Java include platform independence, object-oriented, simple syntax, robust, secure, architecture-neutral, portable, multi-threaded, high performance, and interpreted.3. What is the difference between JDK and JRE?JDK (Java Development Kit) is a development environment used for developing Java applications, which includes the JRE (Java Runtime Environment) and tools required to compile Java code. JRE is the runtime environment for executing Java applications, which includes the Java Virtual Machine (JVM), Java core classes, and supporting libraries.4. What is an exception in Java?An exception in Java is an event that disrupts the normal flow of the program's instructions. It is an error in the program that occurs at runtime. Exceptions in Java arehandled using try, catch, and finally blocks.5. What is the difference between checked and unchecked exceptions in Java?Checked exceptions are exceptions that are checked at compile time and must be either caught or declared in the method signature. Unchecked exceptions are not checked at compiletime and are usually caused by programming errors, such as NullPointerException or ArrayIndexOutOfBoundsException.6. What is the purpose of the main method in Java?The main method is the entry point for any Java application.It is the method that is called when the application starts, and it must be defined with the following signature: public static void main(String[] args).7. What is an interface in Java?An interface in Java is a reference type that is used to specify the behavior of a class. It can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces are used to achieve abstraction and to define a contract that can be implemented by multiple classes.8. What is the difference between abstract class andinterface in Java?An abstract class is a class that cannot be instantiated and may contain both abstract and non-abstract methods. An interface is a completely abstract class that can onlycontain abstract methods, default methods, static methods,and constants. A class can implement multiple interfaces butcan only extend one abstract class.9. What is garbage collection in Java?Garbage collection in Java is the process of automatically identifying and deallocating memory that is no longer in use by the program. The Java Virtual Machine (JVM) has a garbage collector that periodically frees up memory by identifying objects that are no longer reachable.10. What is the purpose of the 'this' keyword in Java?The 'this' keyword in Java is used to refer to the current object. It can be used to access instance variables, methods, and constructors of the current class. It is also used to pass the current object as an argument to another method.11. What is the purpose of the 'super' keyword in Java?The 'super' keyword in Java is used to refer to the parent class or superclass. It can be used to access the variables, methods, and constructors of the parent class. It is also used to call the constructor of the parent class from within a subclass constructor.12. What is the difference between '==’ and 'equals()' method in Java?The '==' operator is used to compare the references of two objects, whereas the 'equals()' method is used to compare the content of two objects. The 'equals()' method can be overridden in a class to provide a custom comparison logic.13. What is encapsulation in Java?Encapsulation in Java is the principle of wrapping the data(variables) and the code acting on the data (methods)together as a single unit. It is one of the fundamental concepts of object-oriented programming and is used torestrict direct access to some of an object's components, which can prevent the accidental modification of data.14. What is the purpose of the 'final' keyword in Java?The 'final' keyword in Java can be used in different contexts: - A final variable cannot be changed once it is assigned.- A final method cannot be overridden by subclasses.- A final class cannot be subclassed.15. What is the purpose of the 'static' keyword in Java?The 'static' keyword in Java is used to create classvariables and methods that are not associated with any object of the class. Static variables and methods belong to theclass itself rather than any particular object. They can be accessed without creating an instance of the class.16. What is a package in Java?A package in Java is a namespace that organizes a set of related classes and interfaces. It is used to group related classes and to avoid naming conflicts. Java packages also provide a level of access control.17. What is。
java英文(第八版)十三章答案.doc
![java英文(第八版)十三章答案.doc](https://img.taocdn.com/s3/m/84aee2b16bd97f192379e957.png)
import java.util.Scanner;public class Exercisel3_2 {public static void main(String[] args) {Sea nner in put = new Sea nn er(System.i n);boolean done = false;int numberl = 0;int number2 = 0;// Enter two integersSystem.out.print「Entertwo integers:");while (!done) {try{nu mberl = input, nextl nt();nu mber2 = in put.nextl nt();done = true;}catch (Exception ex) {System.out.printC1 Incorrect in put and re-e ntertwo in tegers:H); in put. nextLine(); // Discard in put}}System.out.println(”Sum is11 + (numberl + number2));}} public class Exercisel3_4{public static void main(String[] args) {try{new NewLoan⑺5, 30, 100000);NewLoan m = new NewLoa3, 3);new NewLoan(7.5, 30, 20000); }catch (Exception ex){System.out.pri ntln (ex);}System.out.println(”End of program11);}}class NewLoan {private double annuallnterestRate;private int numOfYears;private double loanAmount;/** Default constructor */public NewLoanf) {this(7.5, 30, 100000);}/** Con struct a NewLoa n with spec 讦ied annual in terest rate, number of years and loan amount*/public NewLoan(double annuallnterestRate, int numOfYears,double loanAmount) {if (annuallnterestRate <= 0)throw new lllegalArgumentException「Annual interest rate must be positive.H);讦(numOfYears <= 0)throw new lllegalArgumentException(H Number of years must be positive.H);if (loanAm ount <= 0)throw new lllegalArgume ntExcepti on「Loa n amount must be positive/);setA nnualln terestRate(annuall nterestRate);setNumOfYears(numOfYears);setLoa nAmoun t(loa nAmount);}/** Return annuallnterestRate */public double getAnnuallnterestRate() {return annuallnterestRate;}/** Set a new annuallnterestRate */public void setAnnuallnterestRate(double annuallnterestRate) {if (annuallnterestRate <= 0)throw new Hlega lArgumentException(”Annual interest rate must be positive.H);this.a nnualln terestRate = annualln terestRate;}/** Return numOfYears */public int getNumOfYears() {return numOfYears;}/** Set a new numOfYears */public void setNumOfYears(int numOfYears){讦(numOfYears <= 0)throw new HlegalArgumentExceptionC^umber of years must be positive.11);this.numOfYears = nu mOfYears;}/** Return loanAmount */public double getLoanAmount() {return loanAmount;}/** Set a newloanAmount */public void setLoanAmount(double loanAmount) {if (loanAmount <= 0)throw new lllegalArgume ntExcepti on ("Loa n amount must be positive/); this」o anAmount = loa nAmount;}/** Find monthly payment */public double monthlyPayment() {double monthlylnterestRate = annuallnterestRate / 1200;return loanAmount * monthlyinterestRate / (1 -(Math.pow(l / (1 + monthlylnterestRate), numOfYears * 12))); }/** Find total payment */public double totalPayment() {return monthlyPayment() * numOfYears * 12;}}public class Exercisel3_6 {public static void main(String[] args) {System.out.println(parseHex(,,A5H));System.out.println(parseHex(,l FAA11));System.out.println(parseHe x(Tl(T));System.out.println(parseHex("ABC"));System.out.println(parseHex(,,10A H));}public static int parseHex(String hexString) {int value = con vertHexToDec(hexString.charAt(0));for (int i = 1; i < hexString」ength(); i++) {value = value * 16 + hexString.charAt(i) - O;}return value;}static int convertHexToDec(char ch) {if (ch == TV) {return 10;}else 讦(ch == 'B') {return 11;}else if (ch == 'C') {return 12;}else if (ch == *D') {return 13;}else 讦(ch == 'E') {return 14;}else if (ch == 'F') {retur n 15;}else if (ch <= '9* && ch >= 'O')return ch - O;elsethrow new NumberFormatException(H lllegal character:H + ch);}} public class Exercisel3_8 {public static void main(String[] args) throws HexFormatException{ System.out.println(parseHex(,,A5H));System.out.println(parseHex(,,FAA,'));System.out.printlnfparseHe x(n T10n));System.out.println(parseHex(u ABC"));System.out.println(parseHex(l,10A H));}public static int parseHex(String hexString) throws HexFormatException { int value = conv e rt H exTo Dec( h exSt ri ng.charAt(O));for (int i = 1; i < hexString」ength(); i++) {value = value * 16 + hexString.charAt(i)・'O';}return value;}static int convertHexToDec(char ch) throws HexFormatException {if (ch == TV) {return 10;}else if (ch == •B1) {return 11;}else if (ch == *C') {return 12;}else if (ch == 'D') {return 13;}else if (ch == *E') {return 14;}else 讦(ch == 'F') {return 15;}else if (ch <= '9' && ch >= ’O') return ch - 'O';elsethrow new HexFormatExcepti on ("Illegal hex character:" + ch); }}class HexFormatException extends Exception { HexFormatException() {super(n lllegal hex character");}HexFormatException(String message) {super(message);}} public class Exercisel3_10 {public static void main(String[] args) { try{int[] list = new int[20000000];}catch (Error ex) {ex.pri ntStackTrace();System.out.pri nt In ("You are running out of memory."); }System.out.println("GO");javax.swingJOptionPane.showMessageDialog(null z "Wait"); }}。
java数据结构期末考试题及答案
![java数据结构期末考试题及答案](https://img.taocdn.com/s3/m/dab300d6d1d233d4b14e852458fb770bf78a3bd7.png)
java数据结构期末考试题及答案一、选择题(每题2分,共20分)1. 在Java中,以下哪个类是`java.util`包的一部分?A. ArrayListB. HashMapC. LinkedListD. All of the above答案:D2. 下列哪个方法用于将元素添加到ArrayList的末尾?A. add()B. append()C. push()D. insert()答案:A3. 在Java中,HashMap的键值对映射关系是什么?A. 一对一B. 一对多C. 多对一D. 多对多答案:A4. 下列哪个类是Java集合框架中的接口?A. LinkedListB. HashSetC. ArrayListD. Collection答案:D5. Java中,哪个方法用于删除ArrayList中的指定元素?A. remove()B. delete()C. erase()D. clear()答案:A6. 下列哪个类实现了Queue接口?A. PriorityQueueB. LinkedListC. HashSetD. TreeSet答案:B7. Java中,哪个方法用于判断HashMap是否包含指定的键?A. containsKey()B. containsValue()C. contains()D. hasKey()答案:A8. 下列哪个方法用于获取ArrayList的当前大小?A. size()B. length()C. count()D. lengthOf()答案:A9. 在Java中,哪个类实现了Set接口?A. ArrayListB. LinkedListC. HashSetD. HashMap答案:C10. 下列哪个方法用于将元素插入到ArrayList的指定位置?A. add()B. insert()C. put()D. set()答案:A二、填空题(每题2分,共20分)1. 在Java中,使用________方法可以创建一个ArrayList实例。
java数据结构测试题及答案解析
![java数据结构测试题及答案解析](https://img.taocdn.com/s3/m/0fe810c2900ef12d2af90242a8956bec0975a5f6.png)
java数据结构测试题及答案解析```markdownJava数据结构测试题及答案解析第一章:数组概述数组是一种线性数据结构,用于存储多个相同数据类型的元素。
本章将介绍数组的基本概念和操作。
1.定义数组在Java中,可以使用以下语法定义一个数组:```java<数据类型>[] <数组名> = new <数据类型>[<数组长度>];```2.访问数组元素可以使用索引值来访问数组中的元素,索引值从0开始。
例如,要访问数组中的第一个元素,可以使用以下语法:```java<数组名>[0];```3.数组的常见操作本节将详细介绍数组的常见操作,包括添加元素、删除元素、查找元素等。
3.1 添加元素可以使用以下语法向数组中添加元素:```java<数组名>[<索引值>] = <新元素>;```3.2 删除元素使用以下语法删除数组中的元素:```java<数组名>[<索引值>] = null;```3.3 查找元素可以使用循环语句遍历数组,并通过判断元素的值来查找指定元素。
第二章:链表概述链表是一种常见的数据结构,用于存储多个元素。
本章将介绍链表的基本概念和操作。
1.定义链表在Java中,可以使用以下代码定义一个链表节点:```javaclass ListNode {int val;ListNode next;ListNode(int x) { val = x; }}```2.链表的插入和删除本节将介绍链表的插入和删除操作,包括在链表头插入、在链表尾插入、在指定位置插入等。
2.1 在链表头插入使用以下代码在链表头部插入一个节点:```javaListNode newNode = new ListNode(val); newNode.next = head;head = newNode;```2.2 在链表尾插入使用以下代码在链表尾部插入一个节点:```javaListNode newNode = new ListNode(val); if (head == null) {head = newNode;} else {ListNode curr = head;while (curr.next != null) {curr = curr.next;}curr.next = newNode;}```2.3 删除节点使用以下代码删除链表中的一个节点:```javaListNode prev = null;ListNode curr = head;while (curr != null) {if (curr.val == val) {if (prev == null) {head = curr.next;} else {prev.next = curr.next; }break;}prev = curr;curr = curr.next;}```3.链表的常见操作本节将介绍链表的常见操作,包括查找节点、链表反转等。
数据结构(JAVA)复习题及答案
![数据结构(JAVA)复习题及答案](https://img.taocdn.com/s3/m/16883726b90d6c85ec3ac6b4.png)
一、选择题1、数据结构在计算机内存中的表示是指____A__A.数据的存储结构 B.数据结构C.数据的逻辑结构D.数据元素之间的关系2、若一个算法的时间复杂度用T(n)表示,其中n的含义是(A)A.问题规模B.语句条数C.循环层数D.函数数量3、下列选项中与数据存储结构无关的术语是(D)A.顺序表B.链表C.链队列D.栈4、已知循环队列的存储空间大小为m,队头指针front指向队头元素,队尾指针rear指向队尾元素的下一个位置,则向队列中插入新元素时,修改指针的操作是(D)A.rear=(rear-1)%m;B.front=(front+1)%m;C.front=(front-1)%m;D.rear=(rear+1)%m;5、栈和队列的共同点是__C______A.都是先进后出B.都是先进先出C.只允许在端点处插入和删除元素D.没有共同点6、已知一堆栈的进栈序列为1234,则下列哪个序列为不可能的出栈序列______D__A.1234B.4321C.2143D.41237、具有线性结构的数据结构是(C)A.树B.图C.栈和队列D.广义表8、假设以数组A[60]存放循环队列的元素,其头指针是front=47,当前队列有50个元素,则队列的尾指针值为(B)A.3B.37C.50D.979、若栈采用链式存储结构,则下列说法中正确的是(B)A.需要判断栈满且需要判断栈空B.不需要判断栈满但需要判断栈空C.需要判断栈满但不需要判断栈空D.不需要判断栈满也不需要判断栈空10、若一棵具有n(n>0)个结点的二叉树的先序序列与后序序列正好相反,则该二叉树一定是(C)A.结点均无左孩子的二叉树B.结点均无右孩子的二叉树C.高度为n的二叉树D.存在度为2的结点的二叉树11、若一棵二叉树中度为l的结点个数是3,度为2的结点个数是4,则该二叉树叶子结点的个数是(B)A.4B.5C.7D.812、在n个结点的线索二叉树中,线索的数目为_C_______A.n-1 B.nC.n+1D.2n13、一棵完全二叉树有1001个结点,其中有____B_____叶子结点A.500B.501C.503D.50515、一个有n个顶点的无向图最多有___C____条边。
数据结构英文翻译及答案
![数据结构英文翻译及答案](https://img.taocdn.com/s3/m/0dff461610a6f524ccbf8526.png)
第二题:构造一棵最小生成树,使用prim和kruskal算法。参考P200图7.26 Prim算法构造最小生成树的过程示意图和p202页图7.27 Kruskal算法构造最小生成树的过程示意图,会构造示意图就行。前面两题不涉及到代码。
第三题:
基本思想:
若二叉树为空,则结束统计操作,否则:
中序遍历根的左子树;
统计根节点树;
中序遍历根的右子树。
代码如下:
int count = 0 ; //count定义为全局变量
void Count_tree(BTree t)
{
if(t)
{
Count_Tree(t -> lchild);
Count ++;
Count_Tree(t -> rchild);
写一个算法,traveses链表并摧毁它的值是负的所有节点
如果有问题还请指出,仅供参考。最后一题代码在电脑上测试过,还有简便算法大家共享。
英文翻译:
1、遍历一课树,给出前序,中序,后序。
2、遍历最小生成树上的数字,用prim和kruskal算法
3、设计一个算法,计算二叉树上有多少个节点
4、写一个算法Traveses()链表,删除所有节点的值是负的
}
}
具体内容见书上P145页,这里只写了算法一,也可以写算法二。
第四题:
voidTravel(LinklistH)//函数名可以自己取
{
Linklistpre , q , p;
pre =H;//用于记录遍历的当前节点的前一个位置
p =H-> next;
while(p)
{
java英文试题及答案
![java英文试题及答案](https://img.taocdn.com/s3/m/af64841ca9956bec0975f46527d3240c8447a1ad.png)
java英文试题及答案1. What is the full form of Java?A. Just Another Virtual ApplicationB. Java Application Virtual ArchitectureC. Java Application Virtual ArchitectureD. Just Another Virtual AssistantAnswer: C2. Which of the following is not a feature of Java?A. Platform IndependenceB. RobustnessC. MultithreadingD. Memory ManagementAnswer: D3. What does JRE stand for?A. Java Runtime EnvironmentB. Java Runtime ExecutionC. Java Runtime EngineD. Java Runtime ExpressionAnswer: A4. What is the correct way to declare a variable in Java?A. int number = 10;B. int number = 10.0;C. int number = "ten";D. int number = 10.0f;Answer: A5. Which of the following is a valid Java identifier?A. 2variableB. variable2C. variable$2D. variable2!Answer: B6. What is the default access modifier in Java?A. publicB. privateC. protectedD. defaultAnswer: D7. What is the purpose of the 'this' keyword in Java?A. To call a constructor of the same classB. To call a method of the same classC. To refer to the current objectD. To refer to the parent classAnswer: C8. What is the correct syntax for a 'for' loop in Java?A. for (int i = 0; i < 10; i++)B. for (int i = 10; i > 0; i--)C. for (int i = 0; i <= 10; i++)D. All of the aboveAnswer: D9. What is the output of the following Java code snippet? ```javapublic class Test {public static void main(String[] args) {int x = 10;if (x > 5) {System.out.println("x is greater than 5");} else {System.out.println("x is not greater than 5"); }}}```A. x is greater than 5B. x is not greater than 5C. Compilation errorD. Runtime errorAnswer: A10. Which of the following is not a valid Java data type?A. intB. floatC. doubleD. realAnswer: D。
java数据结构测试题及答案解析
![java数据结构测试题及答案解析](https://img.taocdn.com/s3/m/2d01db10580102020740be1e650e52ea5518cea4.png)
1 下列数据结构中,能用二分法进行查找的是__A____。
A、顺序存储的有序线性表B、线性链表C、二叉链表D、有序线性链表解析:二分法查找只合用于顺序存储的有序表。
在此所说的有序表是指线性表中的元素按值非递减罗列(即从小到大,但允许相邻元素值相等)。
2 在软件设计中,不属于过程设计工具的是__D____。
A、PDL(过程设计语言)B、PAD 图C、N-S 图D、DFD 图解析:软件设计工具包括:程序流程图、 N-S、PAD、HIPO,判定表, PDL(伪码)。
而 DFD(数据流图)属于结构化分析工具。
3 在 switch(expression)语句中, expression 的数据类型不能是__A____。
A、doubleB、charC、byteD、short解析:表达式expression 只能返回这个几种类型的值: int、byte、short 和 char。
多分支语句把表达式返回的值挨次与每一个 case 子句中的值相比较,如果遇到匹配的值,则执行该 case 子句后的语句序列。
4 下列叙述中,错误的是__D____。
A、父类不能替代子类B、子类能够替代父类C、子类继承父类D、父类包含子类5 通过继承实现代码复用:Java 中所有的类都是通过直接或者间接地继承 ng.Object 类得到的。
继承而得到的类称为子类,被继承的类称为父类。
子类不能继承父类中访问权限为 private 的成员变量和方法,子类可以重写父类的方法,及命名与父类同名的成员变量。
子类通过隐藏父类的成员变量和重写父类的方法,把父类的状态和行为改变为自身的状态和行为。
注意:子类中重写的方法和父类中被重写的方法要具有相同的名字,相同的参数表和相同的返回类型,只是函数体不同。
由于子类继承了父类所有的属性(私有的除外),所以子类对象可以作为父类对象使用。
程序中凡是使用父类对象的地方,都可以用子类对象来代替。
一个对象可以通过引用子类的实例来调用子类的方法。
java数据结构期末考试题及答案
![java数据结构期末考试题及答案](https://img.taocdn.com/s3/m/587c438e988fcc22bcd126fff705cc1755275f93.png)
java数据结构期末考试题及答案一、选择题(每题2分,共20分)1. 在Java中,以下哪个类是实现了List接口的?A. ArrayListB. LinkedListC. HashSetD. TreeMap答案:A、B2. 以下哪个方法用于在ArrayList中添加元素?A. add(E e)B. put(E key, V value)C. insert(int index, E element)D. append(E element)答案:A3. 在Java中,哪个类实现了Map接口?A. ArrayListB. HashMapC. HashSetD. LinkedList答案:B4. 以下哪个排序算法的时间复杂度为O(nlogn)?A. 冒泡排序B. 快速排序C. 选择排序D. 插入排序答案:B5. 在Java中,哪个类提供了优先队列的功能?A. PriorityQueueB. LinkedListC. StackD. TreeSet答案:A6. 在Java中,以下哪个方法用于删除LinkedList中的元素?A. remove(Object o)B. poll()C. pop()D. dequeue()答案:A、B7. 在Java中,以下哪个类实现了Set接口?A. ArrayListB. HashSetC. HashMapD. LinkedList答案:B8. 在Java中,哪个类提供了栈的功能?A. StackB. LinkedListC. PriorityQueueD. TreeSet答案:A9. 在Java中,以下哪个方法用于在HashMap中添加键值对?A. add(K key, V value)B. put(K key, V value)C. insert(K key, V value)D. append(K key, V value)答案:B10. 在Java中,以下哪个类实现了SortedSet接口?A. TreeSetB. HashSetC. LinkedHashSetD. ArrayList答案:A二、填空题(每题2分,共20分)1. 在Java中,______类实现了List接口,允许对元素进行索引访问。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
QuestionsThese questions are intended as a self-test for readers.Answers to the questions may be found in Appendix C.1.In many data structures you can________a single record,_________it,and_______it.2.Rearranging the contents of a data structure into a certain order is called_________.30CHAPTER1Overview3.In a database,a field isa.a specific data item.b.a specific object.c.part of a record.d.part of an algorithm.4.The field used when searching for a particular record is the______________.5.In object-oriented programming,an objecta.is a class.b.may contain data and methods.c.is a program.d.may contain classes.6.A classa.is a blueprint for many objects.b.represents a specific real-world object.c.will hold specific values in its fields.d.specifies the type of a method.7.In Java,a class specificationa.creates objects.b.requires the keyword new.c.creates references.d.none of the above.8.When an object wants to do something,it uses a________.9.In Java,accessing an object’s methods requires the_____operator.10.In Java,boolean and byte are_____________.(There are no experiments or programming projects for Chapter1.)Questions31Chapter1,OverviewAnswers to Questions1.insert,search for,delete2.sorting3.c4.search key5.b6.a7.d8.method9.dot10.data typesQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.Inserting an item into an unordered arraya.takes time proportional to the size of the array.b.requires multiple comparisons.c.requires shifting other items to make room.d.takes the same time no matter how many items there are.2.True or False:When you delete an item from an unordered array,in most cases you shift other items to fill in the gap.3.In an unordered array,allowing duplicatesa.increases times for all operations.b.increases search times in some situations.c.always increases insertion times.d.sometimes decreases insertion times.4.True or False:In an unordered array,it’s generally faster to find out an item is not in the array than to find out it is.5.Creating an array in Java requires using the keyword________.6.If class A is going to use class B for something,thena.class A’s methods should be easy to understand.b.it’s preferable if class B communicates with the program’s user.c.the more complex operations should be placed in class A.d.the more work that class B can do,the better.7.When class A is using class B for something,the methods and fields class A can access in class B are called class B’s__________.74CHAPTER2Arrays8.Ordered arrays,compared with unordered arrays,area.much quicker at deletion.b.quicker at insertion.c.quicker to create.d.quicker at searching.9.A logarithm is the inverse of_____________.10.The base10logarithm of1,000is_____.11.The maximum number of elements that must be examined to complete a binary search in an array of200elements isa.200.b.8.c.1.d.13.12.The base2logarithm of64is______.13.True or False:The base2logarithm of100is2.14.Big O notation tellsa.how the speed of an algorithm relates to the number of items.b.the running time of an algorithm for a given size data structure.c.the running time of an algorithm for a given number of items.d.how the size of a data structure relates to the number of items.15.O(1)means a process operates in_________time.16.Either variables of primitive types or_________can be placed in an array. Chapter2,ArraysAnswers to Questions1.d2.True3.b4.False5.new6.d740APPENDIX C Answers to Questions7.interface8.d9.raising to a power10.311.812.613.False14.a15.constant16.objectsuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.puter sorting algorithms are more limited than humans in thata.humans are better at inventing new algorithms.puters can handle only a fixed amount of data.c.humans know what to sort,whereas computers need to be told.puters can compare only two things at a time.2.The two basic operations in simple sorting are_________items and_________ them(or sometimes_________them).3.True or False:The bubble sort always ends up comparing every item with every other item.4.The bubble sort algorithm alternates betweenparing and swapping.b.moving and copying.c.moving and comparing.d.copying and comparing.5.True or False:If there are N items,the bubble sort makes exactly N*N comparisons.Questions1096.In the selection sort,a.the largest keys accumulate on the left(low indices).b.a minimum key is repeatedly discovered.c.a number of items must be shifted to insert each item in its correctlysorted position.d.the sorted items accumulate on the right.7.True or False:If,in a particular sorting situation,swaps take much longer than comparisons,the selection sort is about twice as fast as the bubble sort.8.A copy is________times as fast as a swap.9.What is the invariant in the selection sort?10.In the insertion sort,the“marked player”described in the text corresponds to which variable in the insertSort.java program?a.inb.outc.tempd.a[out]11.In the insertion sort,“partially sorted”means thata.some items are already sorted,but they may need to be moved.b.most items are in their final sorted positions,but a few still need to be sorted.c.only some of the items are sorted.d.group items are sorted among themselves,but items outside the groupmay need to be inserted in it.12.Shifting a group of items left or right requires repeated__________.13.In the insertion sort,after an item is inserted in the partially sorted group,it willa.never be moved again.b.never be shifted to the left.c.often be moved out of this group.d.find that its group is steadily shrinking.110CHAPTER3Simple Sorting14.The invariant in the insertion sort is that________.15.Stability might refer toa.items with secondary keys being excluded from a sort.b.keeping cities sorted by increasing population within each state,in a sortby state.c.keeping the same first names matched with the same last names.d.items keeping the same order of primary keys without regard to secondary keys.Chapter3,Simple SortingAnswers to Questions1.dparing and swapping(or copying)3.False4.a5.False6.b7.False8.three9.Items with indices less than or equal to outer are sorted.10.c11.d12.copies13.b14.Items with indices less than outer are partially sorted.15.buestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.Suppose you push10,20,30,and40onto the stack.Then you pop three items. Which one is left on the stack?2.Which of the following is true?a.The pop operation on a stack is considerably simpler than the remove operation on a queue.b.The contents of a queue can wrap around,while those of a stack cannot.c.The top of a stack corresponds to the front of a queue.d.In both the stack and the queue,items removed in sequence are takenfrom increasingly high index cells in the array.3.What do LIFO and FIFO mean?4.True or False:A stack or a queue often serves as the underlying mechanism on which an ADT array is based.5.Assume an array is numbered with index0on the left.A queue representing a line of movie-goers,with the first to arrive numbered1,has the ticket window on the right.Thena.there is no numerical correspondence between the index numbers andthe movie-goer numbers.b.the array index numbers and the movie-goer numbers increase inopposite left-right directions.c.the array index numbers correspond numerically to the locations in theline of movie-goers.d.the movie-goers and the items in the array move in the same direction.6.As other items are inserted and removed,does a particular item in a queue move along the array from lower to higher indices,or higher to lower?7.Suppose you insert15,25,35,and45into a queue.Then you remove three items.Which one is left?8.True or False:Pushing and popping items on a stack and inserting and removing items in a queue all take O(N)time.174CHAPTER4Stacks and Queues9.A queue might be used to holda.the items to be sorted in an insertion sort.b.reports of a variety of imminent attacks on the star ship Enterprise.c.keystrokes made by a computer user writing a letter.d.symbols in an algebraic expression being evaluated.10.Inserting an item into a typical priority queue takes what big O time?11.The term priority in a priority queue means thata.the highest priority items are inserted first.b.the programmer must prioritize access to the underlying array.c.the underlying array is sorted by the priority of the items.d.the lowest priority items are deleted first.12.True or False:At least one of the methods in the priorityQ.java program (Listing4.6)uses a linear search.13.One difference between a priority queue and an ordered array is thata.the lowest-priority item cannot be extracted easily from the array as it can from the priority queue.b.the array must be ordered while the priority queue need not be.c.the highest priority item can be extracted easily from the priority queue but not from the array.d.All of the above.14.Suppose you based a priority queue class on the OrdArray class in the orderedArray.java program(Listing2.4)in Chapter2,“Arrays.”This will buy you binary search capability.If you wanted the best performance for your priority queue,would you need to modify the OrdArray class?15.A priority queue might be used to holda.passengers to be picked up by a taxi from different parts of the city.b.keystrokes made at a computer keyboard.c.squares on a chessboard in a game program.d.planets in a solar system simulation.Chapter4,Stacks and QueuesAnswers to Questions1.102.bst-In-First-Out;and First-In-First-Out4.False.It’s the other way around.5.b6.It doesn’t move at all.7.458.False.They take O(1)time.9.c10.O(N)11.c12.True13.b14.Yes,you would need a method to find the minimum value.15.aQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.Questions2451.Which of the following is not true?A reference to a class objecta.can be used to access public methods in the object.b.has a size dependant on its class.c.has the data type of the class.d.does not hold the object itself.2.Access to the links in a linked list is usually through the_________link.3.When you create a reference to a link in a linked list,ita.must refer to the first link.b.must refer to the link pointed to by current.c.must refer to the link pointed to by next.d.can refer to any link you want.4.How many references must you change to insert a link in the middle of a singly linked list?5.How many references must you change to insert a link at the end of a singly linked list?6.In the insertFirst()method in the linkList.java program(Listing5.1),the statement newLink.next=first;means thata.the next new link to be inserted will refer to first.b.first will refer to the new link.c.the next field of the new link will refer to the old first link.d.newLink.next will refer to the new first link in the list.7.Assuming current points to the next-to-last link in a singly linked list,what statement will delete the last link from the list?8.When all references to a link are changed to refer to something else,what happens to the link?9.A double-ended lista.can be accessed from either end.b.is a different name for a doubly linked list.c.has pointers running both forward and backward between links.d.has its first link connected to its last link.246CHAPTER5Linked Lists10.A special case often occurs for insertion and deletion routines when a list is ________.11.Assuming a copy takes longer than a comparison,is it faster to delete an item with a certain key from a linked list or from an unsorted array?12.How many times would you need to traverse a singly linked list to delete the item with the largest key?13.Of the lists discussed in this chapter,which one would be best for implementing a queue?14.Which of the following is not true?Iterators would be useful if you wanted toa.do an insertion sort on a linked list.b.insert a new link at the beginning of a list.c.swap two links at arbitrary locations.d.delete all links with a certain key value.15.Which do you think would be a better choice to implement a stack:a singly linked list or an array?Chapter5,Linked ListsAnswers to Questions1.b2.first3.d4.25.16.c7.current.next=null;8.Java’s garbage collection process destroys it.Chapter5,Linked Lists7419.a10.empty11.a linked list12.once,if the links include a previous reference13.a double-ended list14.bually,the list.They both do push()and pop()in O(1)time,but the list uses memory more efficiently.QuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.If the user enters10in the triangle.java program(Listing6.1),what is the maximum number of“copies”of the triangle()method(actually just copies of its argument)that exist at any one time?2.Where are the copies of the argument,mentioned in question1,stored?a.in a variable in the triangle()methodb.in a field of the TriangleApp classc.in a variable of the getString()methodd.on a stack3.Assume the user enters10as in question1.What is the value of n when the triangle()method first returns a value other than1?4.Assume the same situation as in question1.What is the value of n when the triangle()method is about to return to main()?5.True or false:In the triangle()method,the return values are stored on thestack.6.In the anagram.java program(Listing6.2),at a certain depth of recursion,a version of the doAnagram()method is working with the string“led”.When this method calls a new version of itself,what letters will the new version be working with?7.We’ve seen that recursion can take the place of a loop,as in the loop-oriented orderedArray.java program(Listing2.4)and the recursive binarySearch.java program(Listing6.3).Which of the following is not true?a.Both programs divide the range repeatedly in half.b.If the key is not found,the loop version returns because the rangebounds cross,but the recursive version occurs because it reaches thebottom recursion level.c.If the key is found,the loop version returns from the entire method, whereas the recursive version returns from only one level of recursion.d.In the recursive version the range to be searched must be specified in the arguments,while in the loop version it need not be.310CHAPTER6Recursion8.In the recFind()method in the binarySearch.java program(Listing6.3),what takes the place of the loop in the non-recursive version?a.the recFind()methodb.arguments to recFind()c.recursive calls to recFind()d.the call from main()to recFind()9.The binarySearch.java program is an example of the_________approach to solving a problem.10.What gets smaller as you make repeated recursive calls in the redFind() method?11.What becomes smaller with repeated recursive calls in the towers.java program (Listing6.4)?12.The algorithm in the towers.java program involvesa.“trees”that are data storage devices.b.secretly putting small disks under large disks.c.changing which columns are the source and destination.d.moving one small disk and then a stack of larger disks.13.Which is not true about the merge()method in the merge.java program(Listing6.5)?a.Its algorithm can handle arrays of different sizes.b.It must search the target array to find where to put the next item.c.It is not recursive.d.It continuously takes the smallest item irrespective of what array it’s in.14.The disadvantage of mergesort is thata.it is not recursive.b.it uses more memory.c.although faster than the insertion sort,it is much slower than quicksort.d.it is complicated to implement.15.Besides a loop,a___________can often be used instead of recursion. Chapter6,RecursionAnswers to Questions1.102.d3.24.105.false6.“ed”7.b8.c9.divide-and-conquer10.the range of cells to search11.the number of disks to transfer12.c13.b14.b15.stackQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.The Shellsort works bya.partitioning the array.b.swapping adjacent elements.c.dealing with widely separated elements.d.starting with the normal insertion sort.2.If an array has100elements,then Knuth’s algorithm would start with an interval of________.Questions3613.To transform the insertion sort into the Shellsort,which of the following do you not do?a.Substitute h for1.b.Insert an algorithm for creating gaps of decreasing width.c.Enclose the normal insertion sort in a loop.d.Change the direction of the indices in the inner loop.4.True or false:A good interval sequence for the Shellsort is created by repeatedly dividing the array size in half.5.Fill in the big O values:The speed of the Shellsort is more than_______but less than________.6.Partitioning isa.putting all elements larger than a certain value on one end of the array.b.dividing an array in half.c.partially sorting parts of an array.d.sorting each half of an array separately.7.When partitioning,each array element is compared to the_______.8.In partitioning,if an array element is equal to the answer to question7,a.it is passed over.b.it is passed over or not,depending on the other array element.c.it is placed in the pivot position.d.it is swapped.9.True or false:In quicksort,the pivot can be an arbitrary element of the array.10.Assuming larger keys on the right,the partition isa.the element between the left and right subarrays.b.the key value of the element between the left and right subarrays.c.the left element in the right subarray.d.the key value of the left element in the right subarray.11.Quicksort involves partitioning the original array and then_________.362CHAPTER7Advanced Sorting12.After a partition in a simple version of quicksort,the pivot may beed to find the median of the array.b.exchanged with an element of the right subarray.ed as the starting point of the next partition.d.discarded.13.Median-of-three partitioning is a way of choosing the_______.14.In quicksort,for an array of N elements,the partitionIt()method will examine each element approximately______times.15.True or false:You can speed up quicksort if you stop partitioning when the partition size is5and finish by using a different sort.Chapter7,Advanced SortingAnswers to Questions1.c2.403.d4.false5.O(N*logN),O(N2)6.a7.pivot8.d9.true10.c11.partitioning the resulting subarrays12.b13.pivot14.log2N15.trueQuestionsThese questions are intended as a self-test for readers.Answers may be found inAppendix C.1.Insertion and deletion in a tree require what big O time?2.A binary tree is a search tree ifa.every non-leaf node has children whose key values are less than(or equalto)the parent.b.every left child has a key less than the parent and every right child has akey greater than(or equal to)the parent.c.in the path from the root to every leaf node,the key of each node isgreater than(or equal to)the key of its parent.d.a node can have a maximum of two children.3.True or False:Not all trees are binary trees.4.In a complete binary tree with20nodes,and the root considered to be at level 0,how many nodes are there at level4?5.A subtree of a binary tree always hasa.a root that is a child of the main tree’s root.b.a root unconnected to the main tree’s root.c.fewer nodes than the main tree.d.a sibling with the same number of nodes.6.In the Java code for a tree,the______and the_______are generally separate classes.Questions4237.Finding a node in a binary search tree involves going from node to node, askinga.how big the node’s key is in relation to the search key.b.how big the node’s key is compared to its right or left children.c.what leaf node we want to reach.d.what level we are on.8.An unbalanced tree is onea.in which most of the keys have values greater than the average.b.whose behavior is unpredictable.c.in which the root or some other node has many more left children thanright children,or vice versa.d.that is shaped like an umbrella.9.Inserting a node starts with the same steps as_______a node.10.Suppose a node A has a successor node S.Then S must have a key that is larger than_____but smaller than or equal to_______.11.In a binary tree used to represent a mathematical expression,which of the following is not true?a.Both children of an operator node must be operands.b.Following a postorder traversal,no parentheses need to be added.c.Following an inorder traversal,parentheses must be added.d.In pre-order traversal a node is visited before either of its children.12.If a tree is represented by an array,the right child of a node at index n has an index of_______.13.True or False:Deleting a node with one child from a binary search tree involves finding that node’s successor.14.A Huffman tree is typically used to_______text.15.Which of the following is not true about a Huffman tree?a.The most frequently used characters always appear near the top of the tree.b.Normally,decoding a message involves repeatedly following a path fromthe root to a leaf.424CHAPTER8Binary Treesc.In coding a character you typically start at a leaf and work upward.d.The tree can be generated by removal and insertion operations on apriority queue.Chapter8,Binary TreesAnswers to Questions1.O(logN)2.b3.True4.55.c6.node,tree7.a8.cChapter8,Binary Trees7439.finding10.A,A’s left-child descendents11.d12.2*n+113.Falsepress15.cQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.A2-3-4tree is so named because a node can havea.three children and four data items.b.two,three,or four children.c.two parents,three children,and four items.d.two parents,three items,and four children.2.A2-3-4tree is superior to a binary search tree in that it is________.3.Imagine a parent node with data items25,50,and75.If one of its child nodes had items with values60and70,it would be the child numbered__________.4.True or False:Data items are located exclusively in leaf nodes.514CHAPTER102-3-4Trees and External Storage5.Which of the following is not true each time a node is split?a.Exactly one new node is created.b.Exactly one new data item is added to the tree.c.One data item moves from the split node to its parent.d.One data item moves from the split node to its new sibling.6.A2-3-4tree increases its number of levels when________.7.Searching a2-3-4tree does not involvea.splitting nodes on the way down if necessary.b.picking the appropriate child to go to,based on data items in a node.c.ending up at a leaf node if the search key is not found.d.examining at least one data item in any node visited.8.After a non-root node of a2-3-4tree is split,does its new right child contain the item previously numbered0,1,or2?9.A4-node split in a2-3-4tree is equivalent to a_______in a red-black tree.10.Which of the following statements about a node-splitting operation in a2-3 tree(not a2-3-4tree)is not true?a.The parent of a split node must also be split if it is full.b.The smallest item in the node being split always stays in that node.c.When the parent is split,child2must always be disconnected from itsold parent and connected to the new parent.d.The splitting process starts at a leaf and works upward.11.What is the big O efficiency of a2-3tree?12.In accessing data on a disk drive,a.inserting data is slow but finding the place to write data is fast.b.moving data to make room for more data is fast because so many items can be accessed at once.c.deleting data is unusually fast.d.finding the place to write data is comparatively slow but a lot of data can be written quickly.13.In a B-tree each node contains_______data items.Questions51514.True or False:Node splits in a B-tree have similarities to node splits in a2-3 tree.15.In external storage,indexing means keeping a file ofa.keys and their corresponding blocks.b.records and their corresponding blocks.c.keys and their corresponding records.st names and their corresponding keys.Chapter9,Red-Black TreesAnswers to Questions1.in order(or inverse order)2.b3.False4.d5.b6.rotations,changing the colors of nodes7.red8.a9.left child,right child10.d11.a node,its two children12.b13.True14.a15.TrueQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.574CHAPTER11Hash Tablesing big O notation,say how long it takes(ideally)to find an item in a hash table.2.A__________transforms a range of key values into a range of index values.3.Open addressing refers toa.keeping many of the cells in the array unoccupied.b.keeping an open mind about which address to use.c.probing at cell x+1,x+2,and so on until an empty cell is found.d.looking for another location in the array when the one you want is occupied.ing the next available position after an unsuccessful probe is called_____________.5.What are the first five step sizes in quadratic probing?6.Secondary clustering occurs becausea.many keys hash to the same location.b.the sequence of step lengths is always the same.c.too many items with the same key are inserted.d.the hash function is not perfect.7.Separate chaining involves the use of a_____________at each location.8.A reasonable load factor in separate chaining is________.9.True or False:A possible hash function for strings involves multiplying each character by an ever-increasing power.10.The best technique when the amount of data is not well known isa.linear probing.b.quadratic probing.c.double hashing.d.separate chaining.11.If digit folding is used in a hash function,the number of digits in each group should reflect_____________.12.True or False:In linear probing an unsuccessful search takes longer than a successful search.Questions57513.In separate chaining the time to insert a new itema.increases linearly with the load factor.b.is proportional to the number of items in the table.c.is proportional to the number of lists.d.is proportional to the percentage of full cells in the array.14.True or False:In external hashing,it’s important that the records don’t become full.15.In external hashing,all records with keys that hash to the same value are located in___________.Chapter11,Hash TablesAnswers to Questions1.O(1)2.hash function3.d4.linear probing5.1,4,9,16,256.b7.linked listChapter11,Hash Tables7458.1.09.True10.d11.the array size12.False13.a14.False15.the same blockQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.What does the term complete mean when applied to binary trees?a.All the necessary data has been inserted.b.All the rows are filled with nodes,except possibly the bottom one.c.All existing nodes contain data.d.The node arrangement satisfies the heap condition.2.What does the term weakly ordered mean when applied to heaps?3.A node is always removed from the__________.4.To“trickle up”a node in a descending heap meansa.to repeatedly exchange it with its parent until it’s larger than its parent.b.to repeatedly exchange it with its child until it’s larger than its child.c.to repeatedly exchange it with its child until it’s smaller than its child.d.to repeatedly exchange it with its parent until it’s smaller than its parent.5.A heap can be represented by an array because a heap。