JAVA程序設計練習題集答案

1、判斷題

  1. String字符串在建立後能夠被修改。 ( 0 )
  2. 引用一個類的屬性或調用其方法,必須以這個類的對象爲前綴。 ( 0 final 類名 )
  3. 當調用一個正在進行線程的stop()方法時,該線程便會進入休眠狀態。 ( 0 )
  4. 若是一個類聲明實現一個接口,但沒有實現接口中的全部方法,那麼這個類必須是abstract類。 ( 1 )
  5. 構造函數名應與類名相同,返回類型爲void。 ( 0 )
  6. 把數組中元素按某種順序排列的過程叫作查找。 ( 0 )
  7. 對於abstract類,不能建立該類的對象。 ( 1 )
  8. 全部異常都必須捕獲。 ( 0 )
  9. 可使用protected修飾符來防止方法和數據被不一樣包的非子類訪問。 ( 1 )
  10. 在Java程序中,可使用private來修飾一個類。 ( 1 )
  11. 不容許使用final來修飾abstract方法。 ( 0 )
  12. 可使用protected修飾符來防止方法和數據被不一樣包的非子類訪問。 ( 1 )
  13. An event can be defined as a signal to the program that something has happened. ( )
  14. An event is an object created from an event source. ( )
  15. A program cannot choose to ignore an event. ( )
  16. An event in JavaFX is an object of the javafx.event.Event class.。 ( )
  17. InputStream類和OutputStream類是全部二進制I/O的根類。 ( 1 )
  18. InputStream and OutputStream read and write 8-bit data. ( 1 )

2、單選題

  1. Java程序默認引用的包是( b )。
    A.java.awt包
    B.java.lang包
    C.java.util包
    D.java.text包
  2. 如下代碼的輸出結果爲( D )。
public class Pass{    
     static int j = 20;
     public void amethod(int x){
         x = x*2;
         j = j*2;
    }
    public static void main(String args[]){
        int i = 10;	   
        Pass p = new Pass();
        p.amethod(i);
        System.out.println(i+" and "+j); 
  }
}

A.10 and 20
B.錯誤:方法參數與變量不匹配
C.20 and 40
D.10 and 40java

  1. 若A一、A2爲已定義的接口 ,如下接口定義中沒有語法錯誤的是( A ) 。
    A.interface B { void print();}
    B.interface B { void print() { } }
    C.abstract interface B { void print() }
    D.abstract interface B extends A1,A2 { abstract void print(){ };}算法

  2. 將如下哪一種方法插入行3是不合法的。 ( A )
    1.public class Test1{
    2. public float aMethod(float a,float b){ }
    3.
    4.}編程

A.public float aMethod(float c,float d){ }
B.public int aMethod(int a, int b){ }
C.private float aMethod(int a,int b,int c){ }
D.public float aMethod(float a, float b,float c){ }數組

  1. 你怎樣強制對一個對象當即進行垃圾收集? ( E )
    A.調用System.gc(), 同時傳遞要進行垃圾收集對象的引用
    B.調用 Runtime.gc()
    C.給這個對象的全部引用設置一個新的值(例如null)
    D.調用 System.gc()
    E.垃圾收集是不能被強迫當即執行
  2. Which statement about the garbage collection mechanism are true? ( )
    A.The programmer can indicate that a reference through a local variable is no longer of interest.
    B.The programmer has a mechanism that explicity and immediately frees the memory used by Java objects.
    C.Garbage collection require additional programe code in cases where multiple threads are running.
    D.The garbage collection mechanism can free the memory used by Java Object at explection time.
  3. 關於如下程序代碼的說明正確的是( B )。
1class  HasStatic{
2private  static  int  x=1003public  static  void  main(String[  ]  args){ 
4.        HasStatic  hs1=new  HasStatic(  ); 
5.        hs1.x++;
6.        HasStatic  hs2=new  HasStatic(  ); 
7.        hs2.x++;
8.        hs1=new  HasStatic( ); 
9.        hs1.x++;
10.       HasStatic.x--;
11.       System.out.println(「x=+x); 
12} 
13}

A.程序經過編譯,輸出結果爲:x=103
B.程序經過編譯,輸出結果爲:x=102
C.5行不能經過編譯,由於引用了私有靜態變量
D.10行不能經過編譯,由於x是私有靜態變量app

  1. Which of the following statements about the Java keywords is true? ( )
    A.they can never be used as identifiers
    B.they can never be used in comments
    C.they are not case-sensitive
    D.they can also be used as identifiersdom

  2. 方法體內定義的變量稱局部變量,下述關於局部變量的說法中錯誤的是( A )。
    A.局部變量不能與類中的成員變量同名
    B.局部變量未經賦值不能使用
    C.局部變量僅在所定義的代碼塊內(花括號對內)有效
    D.局部變量不能加修飾詞修飾ide

  3. 有一段java 應用程序,它的主類名是a1,那麼保存它的源文件名能夠是( D ).
    A.a1.class
    B.a1
    C.都對
    D.a1.java函數

  4. A JavaFX action event handler contains a method __. ( )
    A.public void actionPerformed(ActionEvent e)
    B.public void handle(Event e)
    C.public void actionPerformed(Event e)
    D.public void handle(ActionEvent e)學習

  5. A JavaFX event handler for event type T is an instance of _. ( )
    A.EventHandler
    B.ActionEvent
    C.Action
    D.EventHandler測試

  6. To handle the mouse click event on a pane p, register the handler with p using __. ( )
    A.p.setOnMouseClicked(handler);
    B.p.setOnMouseReleased(handler);
    C.p.setOnMouseDragged(handler);
    D.p.setOnMousePressed(handler);

  7. Fill in the code below in the underline: ( )

public class Test {
public static void main(String[] args) {
Test test = new Test();
test.setAction(__);
}
public void setAction(T1 t) {
t.m();
}
}
interface T1 {
public void m();
}

A.(e) -> {System.out.print("Action 1! ")}
B.(e) -> System.out.print("Action 1! ")
C.() -> System.out.print("Action 1! ")
D.System.out.print("Action 1! ")

  1. The statement for registering a listener for processing list view item change is _. ( )
    A.lv.getItems().addListener(e -> {processStatements});
    B.lv.addListener(e -> {processStatements});
    C.lv.getSelectionModel().selectedItemProperty().addListener(e -> {processStatements});
    D.lv.getSelectionModel().addListener(e -> {processStatements});
  2. 下面哪一個流類屬於面向字符的輸入流( D ) 。
    A.BufferedWriter
    B.FileInputStream
    C.ObjectInputStream
    D.InputStreamReader
  3. FilterOutputStream is the parent class for BufferedOutputStream, DataOutputStream and PrintStream. Which classes are valid argument for the constructor of a FilterOutputStream? ( )
    A.InputStream
    B.OutputStream
    C.RandomAccessFile
    D.StreamTokenizer
  4. 若是須要從文件中讀取數據,則能夠在程序中建立哪個類的對象( A )。
    A.FileInputStream
    B.FileOutputStream
    C.DataOutputStream
    D.FileWriter
    19.Suppose there is no file Hello.txt in the current directory. Run the program: ( )
import java.io.*;
public class ABC {
	public static void main(String argv[]) throws Exception {
		ABC m=new ABC();
		System.out.println(m.ff());
	}
	
	public int ff() {
		try {
			FileInputStream dis=new FileInputStream("Hello.txt");
		} catch (FileNotFoundException fne) {
			System.out.print("No such file found, ");
			throw fne;
		} finally {
			System.out.print("Doing finally, ");
		}
		return 0;
	}
}

A.No such file found,
B.No such file found ,0
C.No such file found, Doing finally,
D.No such file found, Doing finally, 0

  1. Below is the function header for write() in OutputStream
    void write(int b)
    . Now given code below, what would be the size and the content of the output file?( )
    int i=0xcafebabe;
    FileOutputStream out = new FileOutputStream(「output」);
    out.write(i);
    A.1 byte and 0xbe
    B.1 byte and 0xca
    C.4 bytes as 0xcafebabe
    D.4 bytes as 0xbebafeca
  2. For InputStream.read(), the read() with no parameters, which statement below is correct? ( )
    A.read() returns int, because it has to return EOF to indicate the end of the file
    B.read() returns byte, because it reads a byte from the stream
    C.read() returns char, because it reads a char from the stream
    D.read() returns int, as the number of bytes it just read

3、程序填空題
17. 相同的數組。若是兩個數組list1和list2的內容相同,那麼就說它們是相同的。使用下面的程序能夠判斷兩個數組是否相同,請填空補全程序。

import java.util.*;

public class Main {

   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      int size1 = input.nextInt();
      int[] list1 = new int[size1];
      // Enter values for list1
      for (int i = 0; i < list1.length; i++)
         list1[i] = input.nextInt();

      int size2 = input.nextInt();
      int[] list2 = new int[size2];
      // Enter values for list2
      for (int i = 0; i < list2.length; i++)
         list2[i] = input.nextInt();
      input.close();

      if (equals(list1,list2)) {
         System.out.println("Two lists are identical");
      } else {
         System.out.println("Two lists are not identical");
      }
   }

   public static boolean equals(int[] list1, int[] list2) {

      if (list1.length != list2.length)
	         return false;
      Arrays.sort(list1);
      Arrays.sort(list2);
      for (int i = 0; i < list1.length; i++)
         if (list1[i] != list2[i])
            return false;

      return true;
   }
}

4、函數題

1 建立一個直角三角形類(regular triangle)RTriangle類,實現下列接口IShape。兩條直角邊長做爲RTriangle類的私有成員,類中包含參數爲直角邊的構造方法。
interface IShape {// 接口
public abstract double getArea(); // 抽象方法 求面積
public abstract double getPerimeter(); // 抽象方法 求周長
}
直角三角形類的構造函數原型以下:
RTriangle(double a, double b);
其中 a 和 b 都是直角三角形的兩條直角邊。
裁判測試程序樣例:

import java.util.Scanner;
import java.text.DecimalFormat;

interface IShape {
    public abstract double getArea();

    public abstract double getPerimeter();
}

/*你寫的代碼將嵌入到這裏*/
class RTriangle implements IShape {

	public RTriangle(double a, double b) {
		this.a = a;
		this.b = b;
	}
	public double getArea() {
		return a * b / 2.0;
	}
	public double getPerimeter() {
		return a + b + (Math.sqrt(a * a + b * b));
	}
	private double a;
	private double b;
}

public class Main {
    public static void main(String[] args) {
        DecimalFormat d = new DecimalFormat("#.####");
        Scanner input = new Scanner(System.in);
        double a = input.nextDouble();
        double b = input.nextDouble();
        IShape r = new RTriangle(a, b);
        System.out.println(d.format(r.getArea()));
        System.out.println(d.format(r.getPerimeter()));
        input.close();
    }
}

輸入樣例:
3.1 4.2
輸出樣例:
6.51
12.5202

2.求正n邊形的面積和周長 (10 分)

在一個正n邊形(Regular Polygon)中,全部邊的邊長都相等,且全部角的度數相同(即這個多邊形是等邊、等角的)。咱們已經從下列接口IShape實現了一個正n邊形類RegularPolygon。其構造方法爲:RegularPolygon(int n,double side); 其中n爲邊數,side爲邊長。
從鍵盤輸入正n邊形的邊數n和邊長a,請編程計算該正n邊形的面積和周長。

interface IShape {// 接口
double getArea(); // 求面積
double getPerimeter();// 求周長
}
裁判測試程序樣例:

interface IShape {// 接口

double getArea(); // 求面積

double getPerimeter();// 求周長

}
/* 這裏有正n邊形類RegularPolygon的實現*/

public class Main {
    public static void main(String[] args) {

        /* 你提交的代碼將嵌入到這裏 */ 
        // 相似代碼,簡直是侮辱智商
        Scanner input = new Scanner(System.in);
		double a = input.nextDouble();
		double b = input.nextDouble();
		RTriangle rtt = new RTriangle(a, b);
		System.out.printf("%.4f\n", rtt.getArea());
		System.out.printf("%.4f\n", rtt.getPerimeter());

    }
}

輸入樣例:

在這裏給出一組輸入。例如:
5
7

輸出樣例:

在這裏給出相應的輸出。要求保留4位小數,例如:
84.3034
35

5、編程題

1 求解給定字符串的前綴。

輸入格式:

輸入數目不定的多對字符串,每行兩個,以空格分開。 例如:
filename filepath
Tom Jack

輸出格式:

返回兩個字符串的最大前綴,例如:
The common prefix is file
No common prefix

輸入樣例:

filename filepath
Tom Jack

輸出樣例:

The common prefix is file
No common prefix

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.lang.*;

public class test6 {
	public static void prefix(String s1, String s2) {
		StringBuffer sb = new StringBuffer();
		int shortlen = s1.length() < s2.length() ? s1.length() : s2.length();

		for (int i = 0; i < shortlen; i++) {
			if (s1.charAt(i) == s2.charAt(i))
				sb.append(s1.charAt(i));
			else
				break;
		}
		if (sb.length() == 0)
			System.out.println("No common prefix");
		else
			System.out.println("The common prefix is " + sb);
	}

	public static void main(String[] args) throws IOException {
		StringBuffer sb1 = new StringBuffer();
		StringBuffer sb2 = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			String line = reader.readLine();
			if (line.equals("")) {
				break;
			}
			int i;
			for (i = 0; i < line.length(); i++)
				if (line.charAt(i) == ' ')
					break;
			prefix(line.substring(0, i - 1), line.substring(i + 1, line.length()));
		}
	}
}

(Scanner)input.nextLine() 直接讀取一行 ,不以空格劃分

2 學生類-構造函數

定義一個有關學生的Student類,內含類成員變量: String name、String sex、int age,全部的變量必須爲私有(private)。
(1).編寫有參構造函數:
能對name,sex,age賦值。
(2).覆蓋toString函數:
按照格式:類名 [name=, sex=, age=]輸出。使用idea自動生成,而後在修改爲該輸出格式
(3).對每一個屬性生成setter/getter方法
(4).main方法中
•輸入1行name age sex , 調用上面的有參構造函數新建對象。

輸入樣例:

tom 15 male

輸出樣例:

Student [name=‘tom’, sex=‘male’, age=15]
// 不想寫了,太浪費時間了,就貼一個實驗中作過的題吧,與之相似

設計一個學生類Student,類有成員變量姓名、年齡,有「學習」方法。
Student類派生出本科生類,本科生類派生出研究生類,
本科生類增長專業和學位屬性,覆蓋學習方法。
研究生類增長研究方向屬性,覆蓋學習方法。
每一個類都有顯示方法,用於輸出屬性信息。
編寫測試類測試這三個類。
1. 源代碼:
/*Student 類*/
import java.util.*;
import java.lang.*;
public class Student {
	public Student(String na, int ag) {
		name = na;
		age = ag;
	}
	public void study() {
		System.out.println("I'am a student ,I'am studying !!!!!");
	}
	public void print() {
		System.out.print("name= " + name + " ,age= " + age);
	}
	private String name;
	private int age;
}
/*benke類*/
import java.util.*;
import java.lang.*;
public class benke extends Student {
	public benke(String name,int age,String ma,String deg) {
		super(name,age);
		major = ma ;
		degree = deg;
	}
	@Override
	public void study() {
		System.out.println("I'am a benke ,I'am studying !!!!!");
	}
	public void print() {
		super.print();
		System.out.print(" major= " + major + ", degree= " + degree);
	}
	private String major;
	private String degree;
}
/*Graduate 類*/
import java.util.*;
import java.lang.*;
public class Graduate extends benke {
	public Graduate(String name, int age, String ma, String deg, String dir) {
		super(name, age, ma, deg);
		research_dir = dir;
	}
	@Override
	public void study() {
		System.out.println("I'am a Graduate ,I'am studying !!!!!");
	}
	public void print() {
		super.print();
		System.out.print(" research_dir= " + research_dir);
	}
	private String research_dir;
}
/*測試類*/
import java.util.*;
import java.lang.*;
public class test {
	public static void main(String[] args) {
		Student st = new Student("小王",26);
		st.print();
		System.out.println();
		st.study();
		System.out.println();
		benke  ben = new benke("小張",28,"CS","CS_degree");
		ben.print();
		System.out.println();
		ben.study();
		System.out.println();
		Graduate gg = new Graduate("小劉",36,"藝術","藝術_degree","movie");
		gg.print();
		System.out.println();
		gg.study();
	}
}

3.直角三角形類 (10 分)

建立一個直角三角形類(regular triangle)RTriangle類,實現下列接口IShape。兩條直角邊長做爲RTriangle類的私有成員,類中包含參數爲直角邊的構造方法。

interface IShape {// 接口
// 抽象方法 求面積
public abstract double getArea();
// 抽象方法 求周長
public abstract double getPerimeter(); }
請編程從鍵盤輸入兩條直角邊長值,建立一個直角三角形對象,而後輸出直角三角形的面積和其周長。保留4位小數。

輸入格式:

輸入兩條直角邊長值。例如:3 4。

輸出格式:

在這裏輸出直角三角形的面積和周長。例如: 6 12

輸入樣例:

3.1 4.2

輸出樣例:

6.51
12.5202

import java.util.*;
import java.lang.*;

/*1.接口是隱式抽象的,當聲明一個接口的時候,沒必要使用abstract關鍵字。 2.接口中每個方法也是隱式抽象的,聲明時一樣不須要abstract關鍵字。 3.接口中的方法都是公有的*/

interface IShape { // 接口
	// 抽象方法 求面積
	public abstract double getArea();

	// 抽象方法 求周長
	public abstract double getPerimeter();
}

class RTriangle implements IShape {

	public RTriangle(double a, double b) {
		this.a = a;
		this.b = b;
	}

	public double getArea() {
		return a * b / 2.0;
	}

	public double getPerimeter() {
		return a + b + (Math.sqrt(a * a + b * b));
	}

	private double a;
	private double b;
}

public class test5 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		double a = input.nextDouble();
		double b = input.nextDouble();
		RTriangle rtt = new RTriangle(a, b);
		System.out.printf("%.4f\n", rtt.getArea());
		System.out.printf("%.4f\n", rtt.getPerimeter());
	}

}

4.天不假年

程序填空題。根據題目要求完善下面的代碼。請提交完整代碼。 「今年50,明年18」是一個美好的願望。人的年齡只能不斷增加。 Person類的setAge方法用於更新年齡。 若是新的年齡比原來的年齡小,則輸出B表示發現異常,不然輸出A表示正常。

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int age;
        age = in.nextInt();
        Person p = new Person(age);
        age = in.nextInt();
        try{
            p.setAge(age); 
        }catch(AgeException e){
        }
    }
}
class Person{
   int age;
   public Person(int age){
       this.age = age;
   }
   public void setAge(int age) throws AgeException {
       if(this.age <=age){
          this.age = age;
       }else{
         throw new AgeException();
       }
   }
}
class AgeException extends Exception{
}

輸入格式:

輸入在一行中給出2個絕對值不超過100的正整數A和B。

輸出格式:

在一行中輸出一個字符A或者B。

輸入樣例:

50 18

輸出樣例:

B

import java.util.*;
import java.lang.*;

public class test4 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int age;
		age = in.nextInt();
		Person p = new Person(age);
		age = in.nextInt();
		try {
			p.setAge(age);
		} catch (AgeException e) {
			System.out.println("B");
		} finally {
		}
	}
}

class Person {
	int age;

	public Person(int age) {
		this.age = age;
	}

	public void setAge(int age) throws AgeException {
		if (this.age <= age) {
			this.age = age;
			System.out.println("A");
		} else {
			throw new AgeException();
		}
	}
}

class AgeException extends Exception {
}

5. 找素數 (10 分)

請編寫程序,從鍵盤輸入兩個整數m,n,找出等於或大於m的前n個素數。

輸入格式:

第一個整數爲m,第二個整數爲n;中間使用空格隔開。例如:
103 3

輸出格式:

從小到大輸出找到的等於或大於m的n個素數,每一個一行。例如:
103
107
109

輸入樣例:

9223372036854775839 2

輸出樣例:

9223372036854775907
9223372036854775931

import java.util.*;
import java.lang.*;
import java.math.BigInteger;

public class test3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		BigInteger m = input.nextBigInteger();
		int n = input.nextInt();

		int temp = n;
		for (BigInteger i = m; temp > 0; i = i.add(BigInteger.ONE)) {
			if (isPrime(i)) {
				temp--;
				System.out.println(i);
			}
		}
	}
	public static boolean isPrime(BigInteger a) {
		return a.isProbablePrime(50);
	}
}

6. 大數整除 (10 分)

請編寫程序,從鍵盤輸入一個整數n,找出大於long.MAX_VALUE且能被n整除的前3個數字。

輸入格式:

輸入一個做爲除數的整數n,例如: 17

輸出格式:

輸出大於long.MAX_VALUE且能被n整除的前3個數字,例以下列三個數能被17整除且大於long.MAX_VALUE: 9223372036854775816
9223372036854775833
9223372036854775850

輸入樣例:

103

輸出樣例:

9223372036854775832
9223372036854775935
9223372036854776038

import java.util.*;
import java.lang.*;
import java.math.BigInteger;

public class test2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		int tt = input.nextInt();

		// Long.MAX_VALUE 轉換爲 BigInteger
		BigInteger big = new BigInteger(String.valueOf(Long.MAX_VALUE));

		System.out.println("start......");

		int count = 3;
		while (count != 0) {
			/* * BigInteger mod(BigInteger m) This method returns * a BigInteger whose value is * (this mod m). */
			// intValue() 將BigInteger 轉爲 int
			if (big.mod(BigInteger.valueOf(tt)).intValue() == 0) {
				count--;
				System.out.println(big);
			}
			/* BigInteger ONE: BigInteger的常量 1 */
			big = big.add(BigInteger.ONE); //至關於給 BigInteger+1
		}
		System.out.println("end.......");
	}
}

7. 兩個巨大素數(質數)的乘積 (10 分)

獲得兩個巨大素數(質數)的乘積是簡單的事,但想從該乘積分解出這兩個巨大素數倒是國際數學界公認的質因數分解難題。這種單向的數學關係,是不對稱加密RSA算法的基本原理。 本題給出兩個大素數(128bit位)的乘積和其中一個素數,請你編程求出另外一個素數。

輸入格式:

44022510695404470886511586569647292146578314354528108825807522926455663589709 (大素數的乘積)
189193782774204832019945226750213439577 (其中一個大素數)

輸出格式:

232684764001698545563067004009755869717 (另外一個素數)

輸入樣例:

60883665878129858935918958333091530420746054622405737630613777684610994823161
271963475875372143777333694041058521413

輸出樣例:

223867067745633357281812540202957589797

代碼:

import java.util.*;
import java.lang.*;
import java.math.BigInteger;

public class test1 {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		BigInteger a = input.nextBigInteger();
		BigInteger b = input.nextBigInteger();
		BigInteger c = a.divide(b);
		System.out.println(c);
	}
}
相關文章
相關標籤/搜索