#Java學習#習題五

其他JAVA學習的內容見:目錄

判斷題

1-1.java語言中不用區分字母的大寫小寫。

F

1-2.在Java程序中,可以使用private來修飾一個類。

T

1-3.接口中的方法默認是public abstract方法。

T

1-4.一個類可以實現多個接口。

T

1-5.異常也是一個對象。

T

1-6.Java語言中,變量名可以用漢字表示。

T

1-7.package語句必須放到java程序的最開始。

T

1-8.StringBuffer類是線程安全的,StringBuilder類是線程不安全的。

T

1-9.子類不繼承父類的構造方法。

T

1-10.子類的構造方法必須顯示調用父類的構造方法。

F

單選題

2-1.以下關於構造函數的描述錯誤的是

A.構造函數的返回類型只能是void型。
B.構造函數是類的一種特殊函數,它的方法名必須與類名相同。
C.構造函數的主要作用是完成對類的對象的初始化工作。
D.一般在創建新對象時,系統會自動調用構造函數。

A

2-2.下面哪個對類的聲明是錯誤的

A.class MyClass extends MySuperClass1, MySupperClass2 {}
B.public class MyClass{}
C.abstract class MyClass implements YourInterface1, Youriterface2 {}
D.private class MyClass {} class MyClass extends MySuperClass implements YourInterface {}

A

2-3.下列不可作爲java語言標識符的是()

A.a2
B.$2
C._2
D.22

D

2-4.下面聲明數組的寫法錯誤( )

A.int a[ ];
V.int[ ] a;
C.int[ ][ ] a;
D.int[ ][3] a;

D

2-5.下面哪單詞是Java語言的關鍵字( )。

A.Float
B.this
C.string
D.unsigned

B

2-6.如果需要從文件中讀取數據,則可以在程序中創建哪一個類的對象()。

A.FileInputStream
B.FileOutputStream
C.DataOutputStream
D.FileWriter

A

2-7.下面哪個流類屬於面向字符的輸入流( ) 。

A.BufferedWriter
B.FileInputStream
C.ObjectInputStream
D.InputStreamReader

D

2-8.以下代碼的輸出結果爲( )。

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.錯誤:方法參數與變量不匹配
B.20 and 40
C.10 and 40
D.10 and 20

C

2-9.下列哪個類的聲明是正確的?( )

A.abstract final class HI{}
B.abstract private move(){}
C.protected private number;
D.public abstract class Car{}

D

2-10.下面說法正確的是()

A.如果源代碼中有package語句,則該語句必須放在代碼的第一行
B.如果源代碼中有import語句,則該語句必須放在在代碼的第一行
C.如果源代碼中有main方法,則該方法必須被放在代碼的第一行
D.如果某文件的源代碼中定義了一個public的接口,接口名和文件名可以不同

A

填空題

1

The output of the code below is:

public class Run {
	public static void main(String[] arg) {
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		for ( int i=1; i<5; i++ ) {
			hm.put(i*i, i);
		}
		int sum=0;
		for ( int k: hm.keySet() ) {
			sum += k;
		}
		System.out.println(sum);
	}
}

30

2

The output of the code below is:

public class Foo{ 
	public static void main(String sgf[]){
		StringBuffer a = new StringBuffer("A");
		StringBuffer b = new StringBuffer("B"); 
		System.out.println(""+operate(a,b)+operate(a,b)); 
	} 

	static StringBuffer operate(StringBuffer x,StringBuffer y){ 
		x.append(y); 
		y=x;
		return x;
}}

ABABB

3

請寫出以下程序運行結果:

public class X {  
    public static void main(String [] args) {
        try {
            badMethod();  
            System.out.print("A");  
        } catch (RuntimeException ex) { 
            System.out.print("B"); 
        } catch (Exception ex1) { 
            System.out.print("C"); 
        } finally {
            System.out.print("D"); 
        } 
        System.out.print("E"); 
    } 
    public static void badMethod() { 
        throw new RuntimeException(); 
}}

BDE

4

請寫出以下程序運行結果:

class A
{
	int	x;
	String s;
};
class HelloWorld
{
	public static void main(String[] args) 
	{
		A a= new A();
		System.out.println(a.s);
		System.out.println(a.x);
}}

null

0

5

The output of the code below is:

class Mammal{
       Mammal(){
               System.out.println("Creating Mammal");
       }                 
}

public class Human extends Mammal{ 
public static void main(String argv[]){
       Human h = new Human();
    }
    Human(){
       System.out.println("Creating Human");
    } 
}

Creating Mammal

Creating Human

6

The output of the code below is:

public class Main {
	public static void main(String[] args) {
		String s = "hello";
		try {
			s = s+" world ";
			s.toUpperCase();
			s.trim();
			if ( s.length() <12 ) {
				throw new Exception();
			}
		} catch (Exception e) {
			System.out.print(s);
		} finally {
			System.out.print(s);
		}
	}
}

hello world

程序填空題

1

題目要求:
1.使用this調用已有的有參構造函數,width與length分別爲5和6。
2.爲Rectangle類覆蓋toString。按照width=實際寬度值,length=實際長度值的格式輸出

public Rectangle(){
     width = 5; length = 6;	//第一個空,也可以填this(5,6);
}
public Rectangle(int width, int length) {
    this.width = width;
    this.length = length;
}
public String toString()//第二個空
{
     return "width="+width+",length="+length;//第三個空
}	

2

下列程序使用泛型機制創建一個數組列表對象,並向其添加三個元素,利用迭代器遍歷該數組列表,請把程序補充完整。

import java.util.*;
public class Main{
	public static void main(String[] args) {
		List<String> al=new ArrayList<String>(); //第一個,第二個空
		al.add("red");
		al.add("yellow");
		al.add("blue");
		
		ListIterator< String > listIter=al.listIterator(); 
		while(listIter.hasNext())//第三個空
			System.out.print(listIter.next()+" ");//第四個空
	}
}

編程題

jmu-Java-03面向對象-06-繼承覆蓋綜合練習-Person、Student、Employee、Company

定義Person抽象類,Student類、Company類,Employee類。

Person類的屬性:String name, int age,boolean gender
Person類的方法:
public Person(String name, int age, boolean gender);
public String toString(); //返回"name-age-gender"格式的字符串
public boolean equals(Object obj);//比較name、age、gender,都相同返回true,否則返回falsepublic Person(String name, int age, boolean gender);

Student類繼承自Person,屬性:String stuNo, String clazz
Student類的方法:
//建議使用super複用Person類的相關有參構造函數
public Student(String name, int age, boolean gender, String stuNo, String clazz);
public String toString(); //返回 “Student:person的toString-stuNo-clazz”格式的字符串
public boolean equals(Object obj);//首先調用父類的equals方法,如果返回true,則繼續比較stuNo與clazz。

Company類屬性:String name
Company類方法:
public Company(String name);
public String toString(); //直接返回name
public boolean equals(Object obj);//name相同返回true

Employee類繼承自Person,屬性:Company company, double salary
Employee類方法:
//建議使用super複用Person類的相關有參構造函數
public Employee(String name, int age, boolean gender, double salary, Company company);
public String toString(); //返回"Employee:person的toString-company-salary"格式的字符串
public boolean equals(Object obj);//首先調用父類的equals方法,如果返回true。再比較company與salary。
//比較salary屬性時,使用DecimalFormat df = new DecimalFormat("#.#");保留1位小數

編寫equals方法重要說明:
1.對Employee的company屬性的比較。要考慮傳入爲null的情況。如果company不爲null且傳入爲null,返回false
2.對所有String字符類型比較時,也要考慮null情況。

提示
1.排序可使用Collections.sort
2.equals方法要考慮周全

main方法說明
1.創建若干Student對象、Employee對象。

  • 輸入s,然後依次輸入name age gender stuNo clazz創建Student對象。
  • 輸入e,然後依次輸入name age gender salary company創建Employee對象。
  • 然後將創建好的對象放入List<Person> personList。輸入其他字符,則結束創建。
  • **創建說明:**對於String類型,如果爲null則不創建對象,而賦值爲null。對於company屬性,如果爲null則賦值爲null,否則創建相應的Company對象。

2.對personList中的元素實現先按照姓名升序排序,姓名相同再按照年齡升序排序。提示:可使用Comparable<Person>Comparator<Person>

3.接受輸入,如果輸入爲exitreturn退出程序,否則繼續下面步驟。

4.將personList中的元素按照類型分別放到stuList與empList。注意:不要將兩個內容相同的對象放入列表(是否相同是根據equals返回結果進行判定)。

5.輸出字符串stuList,然後輸出stuList中的每個對象。

6.輸出字符串empList,然後輸出empList中的每個對象。

1-3爲一個測試點 4-6爲一個測試點

輸入樣例:
s zhang 23 false 001 net15
e wang 18 true 3000.51 IBM
s zhang 23 false 001 net15
e bo 25 true 5000.51 IBM
e bo 25 true 5000.52 IBM
e bo 18 true 5000.54 IBM
e tan 25 true 5000.56 IBM
e tan 25 true 5000.51 IBM
s wang 17 false 002 null
s wang 17 false 002 null
e hua 16 false 1000 null
s wang 17 false 002 net16
e hua 16 false 1000 null
e hua 18 false 1234 MicroSoft
!
continue

輸出樣例:
Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:bo-25-true-IBM-5000.52
Employee:hua-16-false-null-1000.0
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Student:wang-17-false-002-null
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Employee:wang-18-true-IBM-3000.51
Student:zhang-23-false-001-net15
Student:zhang-23-false-001-net15
stuList
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Student:zhang-23-false-001-net15
empList
Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Employee:wang-18-true-IBM-3000.51

AC代碼

import java.text.DecimalFormat;
import java.util.*;
 
class Person{
    String name;
    int age;
    boolean gender;
    String str;
    
    public Person(String name, int age, boolean gender,String str) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.str = str;
    }
    
    public String toString() {
        return name+"-"+age+"-"+gender;
    }
    
    public boolean equals(Object obj) {
        Person p = (Person)obj;
        if(p.name==null||this.name==null) {
            return false;
        }
        if(p.name.compareTo(this.name)==0&&p.age==this.age&&p.gender==this.gender) {
            return true;
        }
        return false;
    }
    
    public String getName() {
        return name;
    }
    public int getage() {
        return age;
    }
    public String getStr() {
        return str;
    }
    public boolean getGender() {
        return gender;
    }
}
 
class Student extends Person {
    String stuNo;
    String clazz;
     
    public Student(String name, int age, boolean gender, String str, String stuNo, String clazz) {
        super(name, age, gender, str);
        this.stuNo = stuNo;
        this.clazz = clazz;
    }
    public String toString() {
        return super.toString()+"-"+stuNo+"-"+clazz;
    }
    public boolean equals(Object obj) {
        Student s = (Student)obj;
        if(super.equals(obj)==true) {
            if(this.stuNo==null|this.clazz==null||s.clazz==null||s.stuNo==null) {
                return false;
            }
            if(this.clazz.compareTo(s.clazz)==0&&this.stuNo.compareTo(s.stuNo)==0)
                return true;
        }
        return false;
    }
    public String getStuNo() {
        return stuNo;
    }
    public String getClazz() {
        return clazz;
    }
}
 
class Company{
    String name;
    
    public Company(String name) {
        this.name = name;
    }
    public String toString() {
        return name;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Company c = (Company) obj;
        if(name == null){
            if (c.name != null)
                return false;
        }
        else if(!name.equals(c.name))
            return false;
        return true;
    }
}
 
class Employee extends Person{
    Company company;
    double salary;
    public Employee(String name, int age, boolean gender, String str, Company company, double salary) {
        super(name, age, gender, str);
        this.company = company;
        this.salary = salary;
    }
    
    public String toString() {
        return super.toString()+"-"+company.toString()+"-"+salary;
    }
    
    public boolean equals(Object obj) {
        if(super.equals(obj)==true) {
            Employee e = (Employee)obj;
            if(this.company.toString()==null||e.company.toString()==null) {
                return false;
            }
            String a = new DecimalFormat("#.#").format(this.salary);
            String b = new DecimalFormat("#.#").format(e.salary);
            if(this.company.toString().compareTo(e.company.toString())==0 && a.compareTo(b) == 0){
                return true;
            }
        }
        return false;
    }
    
    public Company getCompany() {
        return company;
    }
    public double getSalary() {
        return salary;
    }
     
}
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        ArrayList<Person> persons = new ArrayList<Person>();
        ArrayList<Student> students = new ArrayList<Student>();
        ArrayList<Employee> employees = new ArrayList<Employee>();
        
        String c;
        String tempString;
        int i, j;
        
        String nameString;
        int age;
        boolean gender;
       
        String stuNoString;  
        String clazzString;
        
        String company;
        double salary;
        
        while(true){
            c = sc.next();
            if(c.compareTo("s")==0){
                nameString = sc.next();
                age = sc.nextInt();
                gender = sc.nextBoolean();
                stuNoString = sc.next();
                clazzString = sc.next();
                Student tempStudent = new Student(nameString, age, gender, c, stuNoString, clazzString);
                persons.add(tempStudent);
            }
            else if(c.compareTo("e")==0){
                nameString = sc.next();
                age = sc.nextInt();
                gender = sc.nextBoolean();
                salary = sc.nextDouble();
                company = sc.next();
                Company company2 = new Company(company);
                Employee tempEmployee = new Employee(nameString, age, gender, c, company2, salary);
                persons.add(tempEmployee);
            }
            else{
                persons.sort(Comparator.comparing(Person::getName).thenComparingInt(Person::getage));
                for(i=0;i<persons.size();i++) {
                    if(persons.get(i).getStr().compareTo("s")==0) {
                        System.out.println("Student:"+persons.get(i).toString());
                        int flag = 0;
                        for(j=0;j<students.size();j++) {
                            if(students.get(j).equals(persons.get(i))) {
                                flag=1;
                                break;
                            }
                        }
                        if(flag == 0) {
                            students.add((Student) persons.get(i));
                        }
                         
                    }else {
                        System.out.println("Employee:"+persons.get(i).toString());
                        int flag = 0;
                        for(j=0;j<employees.size();j++) {
                            if(employees.get(j).equals(persons.get(i))) {
                                flag = 1;
                                break;
                            }
                        }
                        if(flag == 0) {
                            employees.add((Employee)persons.get(i));
                        }
                         
                    }
                }
                tempString = sc.next();
                if(tempString.compareTo("exit")==0||tempString.compareTo("return")==0) {
                    return;
                }
                System.out.println("stuList");
                for(i=0;i<students.size();i++) {
                    System.out.println("Student:"+students.get(i).toString());
                }
                System.out.println("empList");
                for(i=0;i<employees.size();i++) {
                    System.out.println("Employee:"+employees.get(i).toString());
                }
            }
        }
    }
}

字符串反轉

創建一個Java類Demo,它包含一個私有變量字符串str;包含一個私有方法testDemo,該方法能夠將Str反轉(即能夠把字符串Str倒過來)。

輸入格式:
請在這裏寫輸入格式。輸入字符串。

輸出格式:
請在這裏描述輸出格式。輸出字符串。

輸入樣例:
在這裏給出一組輸入。例如:
qingdao

輸出樣例:
在這裏給出相應的輸出。例如:
oadgniq

AC代碼

import java.util.*;

class Demo1{
	private static String str;
	public Demo1(String s)
	{
		str = testDemo(s);
	}
	private static String testDemo(String s)
	{
		int length = s.length();
		String reverse = "";
		for(int i = 0;i < length;i++)
		{
			reverse = s.charAt(i) + reverse;
		}
		return reverse;
	}
	
	public String toString() {
		return str;
	}
}
 
public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String ss = sc.next();
		Demo1 d = new Demo1(ss);
		System.out.println(d.toString());
	}
}
 

圖書價格彙總

圖書價格彙總

輸入格式:
假設某圖書館中圖書記錄的格式爲“Java程序設計: 34;Web程序設計: 56;JSP程序設計:20”(每本書的價格是整數,每本書的價格與下一本書的名字之間有一箇中文;)。

輸出格式:
編寫一個類的方法,能夠接受鍵盤錄入的符合上述格式的圖書內容字符串,輸出圖書記錄中所有書目的總價格。

輸入樣例:
Java程序設計:34 ;Web程序設計: 56;JSP程序設計:20

輸出樣例:
Java程序設計:34
Web程序設計: 56
JSP程序設計:20
總價格爲110

AC代碼

import java.util.*;


public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int sum = 0, tmp = 0;
		String s;
		s = sc.nextLine();
		
		for(int i = 0; i < s.length(); i++){
			if(s.charAt(i) == ';'){
				System.out.println();
			}
			else
				System.out.print(s.charAt(i));
			if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){
				tmp = tmp * 10 + s.charAt(i) - '0';
			}
			else if(i + 1 < s.length()){
				sum += tmp;
				tmp = 0;
			}
			else{
				sum += tmp;
				tmp = 0;
			}
		}
		sum += tmp;
		System.out.println();
		System.out.println("總價格爲"+sum);
	}
}
 

數組元素交換

數組元素交換,要求:(1)最大的元素與第一個元素交換(2)最小的元素與最後一個元素交換。

輸入格式:
輸入一行字符串(由不同的整數組成,以空格分開)

輸出格式:
首先以數組形式輸出初始字符串(一行一個數字),然後以數組形式輸出完成交換後的字符串(一行一個數字)。

輸入樣例:
2 9 0 10

輸出樣例:
2
9
0
10
10
9
2
0

AC代碼

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String[] nums = null;
		nums = sc.nextLine().split(" ");
		int num[] = new int[nums.length];
		int i;
		for(i = 0;i < num.length; i++){
			num[i]=Integer.valueOf(nums[i]);
			System.out.println(num[i]);
		}
		int min = num[0], max = num[0], flagn = 0, flagx = 0;
		for(i = 0; i < num.length; i++){
			if(num[i] < min){
				min = num[i];
				flagn = i;
			}
			if(num[i] > max){
				max = num[i];
				flagx = i;
			}
		}
		
		if(num[0] == min)
			flagn = flagx;
		int a = num[0];
		num[0] = max;
		num[flagx] = a;
		
		if(num[num.length - 1] != min){
			int b = num[num.length - 1];
			num[num.length - 1] = min;
			num[flagn] = b;
		}
		
		for(i = 0;i < num.length; i++){
			System.out.println(num[i]);
		}

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章