当前位置:文档之家› java实验题

java实验题

java实验题
java实验题

实验一基本程序设计

(1)编写一个程序,读入一笔费用与酬金率,计算酬金和总钱数。例如,如果用户输入10作为费用,15%作为酬金率,计算结果显示酬金为¥1.5,总费用为¥11.5。

public class Exercise2_5 {

public static void main(String[] args) {

// Read subtotal

java.util.Scanner input = new java.util.Scanner(System.in);

System.out.print("Enter subtotal: ");

double subtotal = input.nextDouble();

// Read subtotal

System.out.print("Enter gratuity rate: ");

double rate = input.nextDouble();

double gratuity = subtotal * rate / 100;

double total = subtotal + gratuity;

System.out.println("Gratuity is " + gratuity);

System.out.println("Total is " + total);

}

}

(2)(求ASCII码对应的字符)编写程序接受一个ASCII码(从0到128的整数),然后显示它所代表的字符。例如用户输入的是97,程序显示的是俄字符a。 public class Exercise2_8 {

public static void main(String args[]) {

java.util.Scanner input = new java.util.Scanner(System.in);

// Enter an ASCII code

System.out.print("Enter an ASCII code: ");

int code = input.nextInt();

// Display result

System.out.println("The character for ASCII code " + code + " is " + (char)code);

}

}

(3) (计算一个三角形周长)编写程序,读取三角形的三条边,如果输入值合法就计算这个三角形的周长;否则,显示这些输入值不合法。如果任意两条边的和大于第三边,那么输入值都是合法的。

public class Exercise3_25 {

public static void main(String[] args) {

java.util.Scanner input = new java.util.Scanner(System.in);

// Enter three edges

System.out.print(

"Enter three edges (length in double): ");

double edge1 = input.nextDouble();

double edge2 = input.nextDouble();

double edge3 = input.nextDouble();

// Display results

boolean valid = (edge1 + edge2 > edge3) &&

(edge1 + edge3 > edge2) && (edge2 + edge3 > edge1);

if (valid) {

System.out.println("The perimeter of the triangle is " +

(edge1 + edge2 + edge3));

}

else

System.out.println("Input is invalid");

}

}

(4) (解一元二次方程)求一元二次方程ax2 + bx + c = 0的两个根,b就有*b-4ac称作一元二次方程的判别式。如果它是正值,那么一元二次方程俄就有两个正根。如果它为0,方程就只有一个根。如果它是负值,方程无实根。编写程序,提示用户输入a、b和c的值,并且显示基于判别式的结果。如果判别式为正,显示两个根,如果判别式为0,显示一个根,如果判别式为负,显示方程无实根。

(4) import java.util.Scanner;

public class Exercise3_1 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a, b, c: ");

double a = input.nextDouble();

double b = input.nextDouble();

double c = input.nextDouble();

double discriminant = b * b - 4 * a * c;

if (discriminant < 0) {

System.out.println("The equation has no roots");

}

else if (discriminant == 0) {

double r1 = -b / (2 * a);

System.out.println("The root is " + r1);

}

else { // (discriminant > 0)

double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);

double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);

System.out.println("The roots are " + r1 + " and " + r2);

}

}

}

(5)(统计正数和负数的个数,然后计算这些数的平均值)编写程序,读入未指定个数的整数,判断读入的正数有多少个,读入的负数有多少个,然后计算这些输入值的总和及其平均值(不对0计数)。当输入为0时,表示程序结束。将平均值以浮点数显示。

(5)import java.util.Scanner;

public class Exercise4_1 {

public static void main(String[] args) {

int countPositive=0, countNegative = 0;

int count = 0, total = 0, num;

Scanner input = new Scanner(System.in);

System.out.print(

"Enter an int value, the program exits if the input is 0: "); num = input.nextInt();

while (num != 0) {

if (num > 0)

countPositive++;

else if (num < 0)

countNegative++;

total += num;

count++;

// Read the next number

num = input.nextInt();

}

if (count == 0)

System.out.println("You didn't enter any number");

else {

System.out.println("The number of positives is " + countPositive); System.out.println("The number of negatives is " + countNegative); System.out.println("The total is " + total);

System.out.println("The average is " + total * 1.0 / count);

}

}

试验二方法

(1)一个五角数被定义为n(3n-1)/2,其中n=1,2,…。所以,开始的几个数字就是1,5,12,22…,编写下面的方法返回一个五角数:

public static int getPentagonaNumber(int n)

编写一个测试程序显示前100个五角数,每行显示10个。

提示:通过for循环语句打印前100个五角数。

(1)// Exercise5_1.java:

public class Exercise5_1 {

public static void main(String[] args) {

for (int i = 1; i <= 100; i++)

if (i % 10 == 0)

System.out.println(getPentagonalNumber(i));

else

System.out.printf("%10d", getPentagonalNumber(i));

}

public static int getPentagonalNumber(int n) {

return n * (3 * n - 1) / 2;

}

}

(2)编写一个方法,计算一个整数各位数字之和:

public static int sumDigits(long n)

例如:sumDigits(234)返回9(2 + 3 + 4)。

提示:使用求余运算符%提取数字,用/去掉提取出来的数字。例如:使用234%10 (=4)提取4。然后使用234/10(=23)从234中去掉4。使用一个循环来反复提取和去掉每位数字,直到所有的位数都提取完为止。

编写程序提示用户输入一个整数,然后显示这个整数所有数字的和。Remainder(余数)

(2)

public class Exercise5_2 {

public static void main(String[] args) {

java.util.Scanner input = new java.util.Scanner(System.in);

System.out.print("Enter a number: ");

int value = input.nextInt();

System.out.println("The sum of digits for " + value +

" is " + sumDigits(value));

}

public static int sumDigits(long n) {

int temp = (int)Math.abs(n);

int sum = 0;

while (temp != 0) {

int remainder = temp % 10;

sum += remainder;

temp = temp / 10;

}

return sum;

}}

(3) (回文整数)编写下面两个方法:

// Return the reversal of an integer, i.e.reverse(456) returns 654 public static int reverse(int number)

//Return true if number is palindrome

public static boolean ispalindrome(int number)

使用reverse方法实现ispalindrome。如果一个数字的反向倒置数和它的顺向数一样,这个数就称作回文数。编写一个测试程序,提示用户输入一个整数值,然后报告这个整数是否是回文数。

(3)

import java.util.Scanner;

public class Exercise5_3 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a postive integer: ");

int number = input.nextInt();

if (isPalindrome(number))

System.out.println(number + " is palindrome");

else

System.out.println(number + " is not palindrome");

}

public static boolean isPalindrome(int number) {

return number == reverse(number);

}

public static int reverse(int number) {

int result = 0;

while (number != 0) {

int remainder = number % 10;

result = result * 10 + remainder;

number = number / 10;

}

return result;

}

}

(4)创建一个名为MyTriangle的类,它包含如下两个方法:

/** Return true if the sum of any two sides is

* greater than the third side.*/

public static boolean isValid(double side1,double side2,double side3) /** Returns the area of the triangle. */

public static double area(double side1,double side2,double side3)

编写一个测试程序,读入三角形三边的值,若输入有效,则计算面积;否则显示输入无效.

(4)

public class Exercise5_19 {

/** Main method */

public static void main(String[] args) {

java.util.Scanner input = new java.util.Scanner(System.in);

System.out.print(

"Enter the first edge length (double): ");

double edge1 = input.nextDouble();

System.out.print(

"Enter the second edge length (double): ");

double edge2 = input.nextDouble();

System.out.print(

"Enter the third edge length (double): ");

double edge3 = input.nextDouble();

if (MyTriangle.isValid(edge1, edge2, edge3)) {

System.out.println("The are of the triangle is " +

MyTriangle.area(edge1, edge2, edge3));

}

else

System.out.println("Input is invalid");

}

}

class MyTriangle {

public static boolean isValid( double side1, double side2, double side3) {

return (side1 + side2 > side3) &&

(side1 + side3 > side2) && (side2 + side3 > side1);

}

public static double area(double side1, double side2, double side3) { double s = (side1 + side2 + side3) / 2;

return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));

}

}

试验三数组

(1)编写程序,读取10个整数,然后按照和读入顺序相反的顺序将它们显示出来。

提示:int[] num = new int[10]。

(1)

public class Exercise6_2 {

public static void main (String[] args) {

java.util.Scanner input = new java.util.Scanner(System.in);

int[] num = new int[10];

for (int i = 0; i < 10; i++) {

// Read a number

System.out.print("Read a number: ");

num[i] = input.nextInt();

}

// Display the array

for (int i = 9; i >= 0; i--) {

System.out.println(num[i]);

}

}

}

(2)(指定等级)编写一个程序,读入学生成绩,获取最高分best,然后根据下面的规则赋等级值:

如果分数 >= best – 10,等级为A

如果分数 >= best – 20,等级为B

如果分数 >= best – 30,等级为C

如果分数 >= best – 40,等级为D

其他情况下,等级为F

程序提示用户输入学生总数,然后提示用户输入所有的分数,最后显示等级得出结论。

(2)

import java.util.Scanner;

public class Exercise6_1 {

/** Main method */

public static void main(String[] args) {

// Create a Scanner

Scanner input = new Scanner(System.in);

// Get number of students

System.out.print("Enter number of students: ");

int numberOfStudents = input.nextInt();

int[] scores = new int[numberOfStudents]; // Array scores

int best = 0; // The best score

char grade; // The grade

// Read scores and find the best score

System.out.print("Enter " + numberOfStudents + " scores: ");

for (int i = 0; i < scores.length; i++) {

scores[i] = input.nextInt();

if (scores[i] > best)

best = scores[i];

}

// Declare and initialize output string

String output = "";

// Assign and display grades

for (int i = 0; i < scores.length; i++) {

if (scores[i] >= best - 10)

grade = 'A';

else if (scores[i] >= best - 20)

grade = 'B';

else if (scores[i] >= best - 30)

grade = 'C';

else if (scores[i] >= best - 40)

grade = 'D';

else

grade = 'F';

output += "Student " + i + " score is " +

scores[i] + " and grade is " + grade + "\n";

}

// Display the result

System.out.println(output);

}

}

(3) (计算数字的出现次数)编写程序,读取在1到100之间的整数,然后计算每个数出现的次数。假定输入是以0结束的。

(3)public class Exercise6_3 {

public static void main (String[] args) {

java.util.Scanner input = new java.util.Scanner(System.in);

int[] counts = new int[100];

System.out.print("Enter the integers between 1 and 100: ");

// Read all numbers

int number = input.nextInt(); // number read from a file

while (number != 0) {

counts[number - 1]++;

number = input.nextInt();

}

// Display result

for (int i = 1; i < 100; i++) {

if (counts[i] > 0)

System.out.println((i + 1) + " occurs " + counts[i]

+ ((counts[i] == 1) ? " time" : " times"));

}

}

}

(4)编写一个方法,使用下面的方法头求出一个整数数组中的最小元素: public static double min(double[] array)

编写测试程序,提示用户输入10个数字,调用这个方法,返回最小元素值。

(4)public class Exercise6_9 {

// Main method

public static void main(String[] args) {

double[] numbers = new double[10];

java.util.Scanner input = new java.util.Scanner(System.in);

System.out.print("Enter ten double numbers: ");

for (int i = 0; i < numbers.length; i++)

numbers[i] = input.nextDouble();

System.out.println("The min is " + min(numbers));

}

public static double min(double[] list) {

double min = list[0];

for (int i = 1; i < list.length; i++)

if (min > list[i]) min = list[i];

return min;

}

}

(5)编写一个方法,求整数矩阵中所有整数的和,使用下面的方法头:

Public static double sumMatrix(int[][] m)

编写一个测试程序,读取一个4 X 4的矩阵,然后显示所有元素的和。

(5)import java.util.Scanner;

public class Exercise7_1 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a 4 by 4 matrix row by row: ");

double[][] m = new double[4][4];

for (int i = 0; i < 4; i++)

for (int j = 0; j < 4; j++)

m[i][j] = input.nextDouble();

System.out.print("Sum of the matrix is " + sumMatrix(m));

}

public static double sumMatrix(double[][] m) {

int sum = 0;

for (int i = 0; i < m.length; i++)

for (int j = 0; j < m[0].length; j++)

sum += m[i][j];

return sum;

}

}

试验四对象和类

(1)(矩形类Rectangle) 遵从8.2节中Circle类的例子,设计一个名为Rectangle的类表示矩形。这个类包括:

1)两个名为width和height的double型数据域,它们分别表示矩形的宽和高。width和height的默认值都是1。

2)创建默认矩形的无参构造方法。

3)一个创建width和height为指定值的矩形的构造方法。

4)一个名为getArea()的方法返回矩形的面积。

5)一个名为getPerimiter()的方法返回周长。

画出该类的UML图。实现这个类。编写一个测试程序,创建两个Rectangle对象----一个矩形宽为4而高为40,另一个矩形宽为3.5而高为35.9。依照每个矩形的宽、高、面积和周长的顺序显示。

(1)public class Exercise8_1 {

public static void main(String[] args) {

Rectangle myRectangle = new Rectangle(4, 40);

System.out.println("The area of a rectangle with width " +

myRectangle.width + " and height " +

myRectangle.height + " is " +

myRectangle.getArea());

System.out.println("The perimeter of a rectangle is " +

myRectangle.getPerimeter());

Rectangle yourRectangle = new Rectangle(3.5, 35.9);

System.out.println("The area of a rectangle with width " +

yourRectangle.width + " and height " +

yourRectangle.height + " is " +

yourRectangle.getArea());

System.out.println("The perimeter of a rectangle is " +

yourRectangle.getPerimeter());

}

}

class Rectangle {

// Data members

double width = 1, height = 1;

// Constructor

public Rectangle() {

}

// Constructor

public Rectangle(double newWidth, double newHeight) {

width = newWidth;

height = newHeight;

}

public double getArea() {

return width * height;

}

public double getPerimeter() {

return 2 * (width + height);

}

}

(2)(账户类Account)设计一个名为Account的类,它包括:

●一个名为id的int类型私有账户数据域(默认值为0)。

●一个名为balance的double类型私有账户数据域(默认值为0)。

●一个名为annualInterestRate的double类型私有数据域存储当前利率(默

认值为0)。假设所有的账户都有相同的利率。

●一个名为dateCreated的Date 类型私有数据域存储账户的开户日期。

●一个能创建默认账户的无参构造方法。

●一个能创建带特定id和初始余额的账户的构造方法。

●Id,balance, annualInterestRate的访问器和修改器。

●dateCreated的访问器。

●一个名为getMonthlyInterestRate()的方法返回月利率。

●一个名为withdraw的方法从账户提取特定数额。

●一个名为deposit的方法向账户存储特定数额。

画出该类的UML图。实现这个类。编写一个测试程序,创建一个账户ID为1122、余额为20000美元、年利率为4.5%的Account对象。使用withdraw 方法取款2500美元,使用diposit方法存款3000美元,然后打印余额、月利息以及这个账户的开户日期。

提示:月利率 annualInterestRate/1200

(2)

public class Exercise8_7 {

public static void main (String[] args) {

Account account = new Account(1122, 20000);

Account.setAnnualInterestRate(4.5);

account.withdraw(2500);

account.deposit(3000);

System.out.println("Balance is " + account.getBalance());

System.out.println("Monthly interest is " +

account.getMonthlyInterest());

System.out.println("This account was created at " +

account.getDateCreated());

}

}

class Account {

private int id;

private double balance;

private static double annualInterestRate;

private java.util.Date dateCreated;

public Account() {

dateCreated = new java.util.Date();

}

public Account(int newId, double newBalance) {

id = newId;

balance = newBalance;

dateCreated = new java.util.Date();

}

public int getId() {

return this.id;

}

public double getBalance() {

return balance;

}

public static double getAnnualInterestRate() {

return annualInterestRate;

}

public void setId(int newId) {

id = newId;

}

public void setBalance(double newBalance) {

balance = newBalance;

}

public static void setAnnualInterestRate(double newAnnualInterestRate) {

annualInterestRate = newAnnualInterestRate;

}

public double getMonthlyInterest() {

return balance * (annualInterestRate / 1200);

}

public java.util.Date getDateCreated() {

return dateCreated;

}

public void withdraw(double amount) {

balance -= amount;

}

public void deposit(double amount) {

balance += amount;

}

}

(3)、(风扇类Fan)设计一个名为Fan的类来表示一个风扇。这个类包括: 三个名为SLOW、MEDIUM、和FAST而值为1、2、3的常量表示风扇

的速度。

●一个名为speed的int类型私有数据域表示风扇的速度(默认值为SLO

W)。

●一个名为on的boolean类型私有数据域表示风扇是否打开(默认值为fa

lse)。

●一个名为radius的double类型私有数据域表示风扇的半径(默认值

为5)

●一个名为color的string类型数据域表示风扇的颜色(默认值为

blue)。

●这四个数据域的访问器和修改器。

●一个创建默认风扇的无参构造方法。

●一个名为toString()的方法返回描述风扇的字符串。如果风扇是打开的,那

么该方法在一个组合的字符串中返回风扇的速度、颜色和半径。如果风扇没有打开,该方法就返回一个由“fan is off”和风扇颜色及半径组合成的字符串。

画出该类的UML图。实现这个类。编写一个测试程序,创建两个Fan对象。将第一个对象设置为最大速度、半径为10、颜色为yellow、状态为打开。将第二个对象设置为中等速度、半径为5、颜色为blue、状态为关闭。通过调用它们的toString方法显示这些对象。

(3)

public class Exercise8_8 {

public static void main(String[] args) {

Fan1 fan1 = new Fan1();

fan1.setSpeed(Fan1.FAST);

fan1.setRadius(10);

fan1.setColor("yellow");

fan1.setOn(true);

System.out.println(fan1.toString());

Fan1 fan2 = new Fan1();

fan2.setSpeed(Fan1.MEDIUM);

fan2.setRadius(5);

fan2.setColor("blue");

fan2.setOn(false);

System.out.println(fan2.toString());

}

}

class Fan1 {

public static int SLOW = 1;

public static int MEDIUM = 2;

public static int FAST = 3;

private int speed = SLOW;

private boolean on = false;

private double radius = 5;

private String color = "white";

public Fan1() {

}

public int getSpeed() {

return speed;

}

public void setSpeed(int newSpeed) {

speed = newSpeed;

}

public boolean isOn() {

return on;

}

public void setOn(boolean trueOrFalse) {

this.on = trueOrFalse;

}

public double getRadius() {

return radius;

}

public void setRadius(double newRadius) { radius = newRadius;

}

public String getColor() {

return color;

}

public void setColor(String newColor) {

color = newColor;

}

public String toString() {

return "speed " + speed + "\n"

+ "color " + color + "\n"

+ "radius " + radius + "\n"

+ ((on) ? "fan is on" : " fan is off");

}

}

(4)、(二次方程式)为二次方程式ax2 + bx + c = 0设计一个名为QuadraticEquation的类。这个类包括;

●代表三个系数的私有数据域a、b和c。

●一个参数为a、b和c的构造方法。

●a、b、c的三个get方法。

●一个名为getDiscriminant()的方法返回判别式,b2-4ac。

●一个名为getRoot1()和getRoot2()的方法返回等式的两个根:这些方

法只有在判别式为非负数时才有用。如果判别式为负,这些方法返回0。画出该类的UML图。实现这个类。编写一个测试程序,提示用户输入a、b、c 的值,然后显示判别式的结果。如果判别式为正数,显示两个根;如果判别式为0,显示一个根;否则,显示“The equation has no roots.”

(4)

import java.util.Scanner;

public class Exercise8_10 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a, b, c: ");

double a = input.nextDouble();

double b = input.nextDouble();

double c = input.nextDouble();

QuadraticEquation equation = new QuadraticEquation(a, b, c);

double discriminant = equation.getDiscriminant();

if (discriminant < 0) {

System.out.println("The equation has no roots");

}

else if (discriminant == 0)

{

System.out.println("The root is " + equation.getRoot1());

}

else // (discriminant >= 0)

{

System.out.println("The roots are " + equation.getRoot1()

+ " and " + equation.getRoot2());

}

}

}

class QuadraticEquation {

private double a;

private double b;

private double c;

public QuadraticEquation(double newA, double newB, double newC) {

a = newA;

b = newB;

c = newC;

}

double getA() {

return a;

}

double getB() {

return b;

}

double getC() {

return c;

}

double getDiscriminant() {

return b * b - 4 * a * c;

}

double getRoot1() {

if (getDiscriminant() < 0)

return 0;

else {

return (-b + getDiscriminant()) / (2 * a);

}

}

double getRoot2() {

if (getDiscriminant() < 0)

return 0;

else {

return (-b - getDiscriminant()) / (2 * a);

}

}

}

试验五字符串和文本I/O

1、编写程序,提示用户输入一个社会保险号码,它的格式是DDD-DD-DDDD,其

中D是一个数字。程序会为正确的社保号显示“valid SSN”,否则,显示“invalid SSN”.

(1)

public class Exercise9_1 {

public static void main(String[] args) {

// Prompt the user to enter a string

java.util.Scanner input = new java.util.Scanner(System.in);

System.out.print("Enter a string for SSN: ");

String s = input.nextLine();

if (isValidSSN(s)) {

System.out.println("Valid SSN");

}

else {

System.out.println("Invalid SSN");

}

}

/** Check if a string is a valid SSN */

public static boolean isValidSSN(String ssn) {

return ssn.length() == 11 &&

Character.isDigit(ssn.charAt(0)) &&

Character.isDigit(ssn.charAt(1)) &&

Character.isDigit(ssn.charAt(2)) &&

ssn.charAt(3) == '-' &&

Character.isDigit(ssn.charAt(4)) &&

Character.isDigit(ssn.charAt(5)) &&

ssn.charAt(6) == '-' &&

Character.isDigit(ssn.charAt(7)) &&

Character.isDigit(ssn.charAt(8)) &&

Character.isDigit(ssn.charAt(9)) &&

Character.isDigit(ssn.charAt(10));

}

}

2、编写一个方法,将一个十进制数转换为一个二进制数。方法头如下所示:public static String decimalToBinary(int value)

编写一个测试程序,提示用户输入一个十进制整数,然后显示对应的二进制数。提示:用StringBuffer存储字符串,然后再把Stringbuffer对象转换为String 类。

(2)

public class Exercise9_10 {

public static void main(String[] args) {

// Prompt the user to enter a string

java.util.Scanner input = new java.util.Scanner(System.in);

System.out.print("Enter an integer: ");

int value = input.nextInt();

System.out.println("The binary value is " + decimalToBinary(value)); }

public static String decimalToBinary(int value) {

StringBuffer buffer = new StringBuffer();

while (value != 0) {

int bit = value % 2;

buffer.insert(0, bit);

value = value / 2;

}

return buffer.toString();

}

}

3、(求字符串中大写字母的个数)编写程序,传给main方法一个字符串,显示该字符串中大写字母的个数。

提示:从命令行读取参数。Java Test args[0] args[1] args[3]

(3)

public class Exercise9_15 {

public static void main(String[] args) {

// Check command-line arguments

if (args.length != 1) {

System.out.println(

"Usage: java Exercise9_15 string");

System.exit(0);

}

String s = args[0];

int total = 0;

for (int i = 0; i < s.length(); i++) {

if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')

total++;

}

System.out.println("The number of uppercase letters is " +

total);

}

}

4、(写/读数据)编写一个程序,如果名为Exercise9_19.txt的文件不存在,则创建该文件。使用文本I/O编写随机产生100个整数给文件。文件中的数据由空格分开。从文件中读回数据然后显示排好序的数据。

提示:在main方法头抛出异常。

public static void main(String[] args) throws Exception{ }

(4)

import java.util.*;

import java.io.*;

public class Exercise9_19 {

public static void main(String[] args) throws Exception {

// Check if source file exists

File file = new File("Exercise9_19.txt");

if (!file.exists()) {

// Create the file

PrintWriter output = new PrintWriter(file);

for (int i = 1; i <= 100; i++) {

output.print((int)(Math.random() * 100) + " ");

}

output.close();

}

Scanner input = new Scanner(file);

int[] numbers = new int[100];

for (int i = 0; i < 100; i++)

numbers[i] = input.nextInt();

Arrays.sort(numbers);

for (int i = 0; i < 100; i++)

System.out.print(numbers[i] + " ");

}

}

试验六继承和多态

1、设计一个名为MyPoint的类,表示一个带x坐标和y坐标的点。该类包括:

●两个带get方法的数据域x和y,分别表示它们的坐标。

●一个创建点(0,0)的无参构造方法。

●一个创建特定坐标点的构造方法。

●两个数据域x和y各自得get方法。

●一个名为distance的方法,返回MyPoint类型的两个点之间的距离。

●一个名为distance的方法,返回指定x和y坐标的两个点之间的距离。

画出该类的UML图。实现这个类。编写一个测试程序,创建两个点(0,0)和(10,30.5) ,并显示它们之间的距离。

1、

public class Exercise10_4 {

public static void main(String[] args) {

MyPoint p1 = new MyPoint();

Java上机练习题

Java 复习题 第一章 1、分别用Java应用程序和Java小程序编写程序:在屏幕上输出“Hello,欢迎来到精彩的 Java世界!”。 程序:①应用程序:HelloWorld1.java ②小程序:HelloWorld.java和A.htm Java 应用程序: 《HelloWorld1.java》 public class HelloWorld1{ public static void main(String[] args){ System.out.println("Hello,欢迎来到精彩的Java世界!"); } } Java 小程序: 《HelloWorld.java》 import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet{ public void paint(Graphics g){ g.drawString("Hello,欢迎来到精彩的Java世界!",2,20); } } 《A.htm》 我的第一个JAVA Applet程序 第二章 1、26页案例3:TriangleArea.java(三角形面积) 编写一个java程序,已知三角形三边边长,求三角形面积。要求三条边长从控制台输入。其中4,3,6分别代表三角形的三条边。 《TriangleArea.java》 public class TriangleArea{ public static void main(String[] args){ double a=Double.parseDouble(args[0]); double b=Double.parseDouble(args[1]); double c=Double.parseDouble(args[2]); if(a+b<=c||a+c<=b||b+c<=a)

浙大JAVA 实验题答案05answer1

实验5 分支结构程序的设计 1.程序填空题,不要改变与输入输出有关的语句。 20004 计算旅途时间 输入2个整数time1和time2,表示火车的出发时间和到达时间,计算并输出旅途时间。 有效的时间范围是0000到2359,不需要考虑出发时间晚于到达时间的情况。 例:括号内是说明 输入 712 1411(出发时间是7:12,到达时间是14:11) 输出 The train journey time is 6 hrs 59 mins. import java.util.Scanner; public class Test20004 { public static void main(String[] args) { Scanner in=new Scanner(System.in); int time1, time2, hours, mins; time1=in.nextInt(); time2=in.nextInt(); /*------------------*/ /*计算两个时间之间的小时数和分钟数*/ hours=time2/100-time1/100; mins=time2%100-time1%100; /*当计算得到的分钟数为负数时进行调整*/ hours=mins>0?hours:hours-1; mins=mins>0?mins:mins+60; //或:if(mins<0){hours-=1;mins+=60;} System.out.println("The train journey time is "+hours+" hrs "+ mins+" mins."); } } 30001 显示两级成绩 输入一个正整数repeat (0

java上机练习题

要求:代码规范,代码风格,思路正确,功能实现 1、设计一个能随机产生100个大写英文字母的方法,在该方法中统计产生了多少元音字母,并输出这个数字。 2、编写一个矩形类Rect,包含: 两个protected属性:矩形的宽width;矩形的高height。 两个构造器方法: (1)一个带有两个参数的构造器方法,用于将width和height属性初化; (2)一个不带参数的构造器,将矩形初始化为宽和高都为10。 两个方法: (1 求矩形面积的方法area() (2 求矩形周长的方法perimeter() 4.编写一个Java源程序,在程序中建立一个含10个整型(int)元素的一维数组,对数组中的每个元素赋值,然后按下标的逆序输出。 5. 设计一个圆类(Circle),将圆的位置(圆心坐标和半径)作为属性(提供任意圆的设置),并能计算圆的面积。 Circle类必须满足以下要求: (1) 圆类Circle 的属性有: cPoint_x : int型,代表圆心横坐标。 cPoint_y : int型,代表圆心纵坐标。 cRadius: double型,代表圆的半径。 cPI: double型,最终静态变量初值为3.14,代表圆的圆周率。 cArea: double型,代表圆的面积。 (2) 圆类Circle 的方法有: Circle ( ) : 构造函数,将圆的圆心置坐标原点,半径置1。 Circle ( int x , int y, double r) : 构造函数,形参 r 为半径的初值,x为横坐标的初值,y为纵坐标的初值。 double cAreaCount() : 计算当前圆类对象的面积并赋值给Circle类的cArea属性,返回cArea的值给此方法的调用者。 String toString( ) : 把当前圆类对象的圆心坐标、半径以及面积组合成“圆心为(x, y)半径为r的圆的面积为cA”字符串形式,其中x、 y、r和cA分别为横坐标、纵坐标、半径和面积的数据。 7、猜数游戏 随机生成一个数 输入一个数 如果比随机生成的数大,显示“猜错了,比这个数小” 如果比随机生成的数小,显示“猜错了,比这个数大” 如果相等,显示“恭喜你,答对了” 8、写一个彩票程序

java上机实验

一、实验内容描述(问题域描述) 实验目的:熟悉JDK的安装、配置和使用,掌握Java Application程序的基本结构。 实验内容: (1)安装JDK,并练习设置JAVA_HOME、path和classpath环境变量;(2)编写一个打印出”HelloWorld”的Java Application程序,并编译运行 二、实验设计(包括实验方案设计,实验手段的确定,实验步骤,实验过程等)

一. 实验内容描述(问题域描述) :熟悉Java的各种类型、掌握java的变量定义及表达式的运算等。 实验内容: (1)编写一个程序计算长方形的面积和周长。长方形的宽和高要求从键盘输入。 (2)尝试使用Math类提供的随机数生成方法,产生一个1~100的随机整数并输出。 import java.util.Scanner; public class Juxing { public static void main(String[] args) { // TODO Auto-generated method stub int s=0,l=0; Scanner sc= new Scanner(System.in); System.out.println("请输入长h,回车换行"); int h=sc.nextInt(); System.out.println("请输入宽w,回车换行"); int w=sc.nextInt(); s=h*w; l=2*(h+w); System.out.println("长方形面积为s="+s); System.out.println("长方形周长为l="+l); } } 2. public class shuzi { public static void main(String[] args) { // TODO Auto-generated method stub System.out.print((int)(Math.random()*100)); }

java第二次实验报告

java实验报告 实验题目运用JavaFx实现时钟动画学生姓名 指导教师 学院 专业班级 完成时间2014年12

目录 一、实验目的 (3) 二、实验开发环境和工具 (3) 三、实验内容 (3) 四.实际简要描述: (3) 五.程序清单 (4) 六.结果分析 (10) 七.调试报告 (11) 八.实验心得 (11)

一、实验目的 1.了解和掌握JavaFx动画基本概念和相关用法 二、实验开发环境和工具 可以在Linux或者Windows操作系统上搭建开发环境,可使用集成开发环境Eclipse,使用Java语言,工具包使用JDK1.8。 三、实验内容 基于JavaFx画出如下所示可动态变化的时钟。要求按‘start’按钮可启动时钟,按‘stop’按钮可让时钟暂停。时钟初始时显示当前时间并开始动态变化。 四.实际简要描述: 1.新建一个动态时针 EventHandlereventHandler = e -> { clock.setCurrentTime(); // 设置时钟时间 }; 2.建立一个动画使时钟走起来 Timeline animation = new Timeline( newKeyFrame(https://www.doczj.com/doc/e915464696.html,lis(1000), eventHandler)); animation.setCycleCount(Timeline.INDEFINITE); animation.play(); // 开始动画

3.建立按钮 HBoxhbox=new HBox();//新建HBOX布局 hbox.setSpacing(20); hbox.setLayoutX(310); hbox.setLayoutY(520); Start = new Button("Start");//建立start按钮 Start.setPrefSize(80, 40); Stop = new Button("Stop");//建立stop按钮 Stop.setPrefSize(80, 40); hbox.getChildren().addAll(Start,Stop);//将按钮加入HBOX getChildren().add(hbox); 五.程序清单 importjavafx.application.Application; importjava.util.Calendar; importjava.util.GregorianCalendar; https://www.doczj.com/doc/e915464696.html,yout.Pane; importjavafx.scene.paint.Color; importjavafx.scene.shape.Circle; importjavafx.scene.shape.Line; importjavafx.scene.text.Text; importjavafx.application.Application; importjavafx.stage.Stage; importjavafx.animation.KeyFrame; importjavafx.animation.Timeline; importjavafx.event.ActionEvent;

Java实验题目

Java实验题目 一、 (1).编写Java应用程序,定义byte、short、int、long、float、double、char和boolean 等类型的数据并用一个输出语句输出,要求每行输出一个数据。 (2).编写Java小应用程序,输出两行字符串:“Java很有趣。”和“努力学习Java 编程。”,输出的起点坐标是(20,20),行距是50像素。 (3).使用算术运算符得到一个4位十进制数的各位数字并输出,然后输出该数的逆序数和各位数字平方后相加的和。 (4).编写Java小应用程序,用三目条件运算符求程序中给定的4个double数的最大值和最小值并输出结果。 实验报告题:使用算术运算符得到一个4位十进制数的各位数字并输出,然后输出该数的逆序数和各位数字平方后相加的和。 二、 1、数据类型与表达式的使用 自己编写程序测试各种运算符的使用。例如,以下程序是测试Java的数据类型:public class UseVarible { public static void main(String args []) { boolean b = true; short si = 128; int i = -99; long l = 123456789L; char ch = 'J'; float f = 3.1415925F; double d = -1.04E-5; String s = "你好!"; System.out.println("布尔型变量b="+ b); System.out.println("短整型变量si="+ si); System.out.println("整型变量i="+ i); System.out.println("长整型变量l="+ l); System.out.println("字符型变量ch="+ ch); System.out.println("浮点型变量f="+ f); System.out.println("双精度型变量d="+ d); System.out.println("字符型对象s="+ s); } } 2、数组的创建与使用 编写并运行P.23例1-5,例1-6。 3、思考与上机练习 (1). 编写Java应用程序,其中定义一个int数组(数组元素任意指定),将数组

java实验答案解读

实验一 水仙花数: class shuixianhua {//水仙花数 public static void main(String arg[]) { int i,a,a1,b,b1,c; for(i=100;i<1000;i++) { a=i%10; a1=i/10; b=a1%10; b1=a1/10; c=b1%10; if(i==(a*a*a+b*b*b+c*c*c)) System.out.println(i); } } } 输出如下: 153 370 371 407 打印出100以内素数: public class sushu { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int i,j,k=0; for(i=2;i<100;i++){ if(i==2) System.out.println(i); i++; for(j=2;j

k=1; } if(k==1) System.out.println(i); } } 求1!+2!+ (20) public class jiecheng { public static void main(String[] args) { int i,sum=0,k; for(i=1;i<=20;i++) { k=ji(i); sum=k+sum; } System.out.print(sum); } static int ji(int n) { if(n==1) return 1; else return ji(n-1)*n; } } 习题2.6 public class Test{ public static void main(String[] args)//第19题,打出图形.菱形{ int n=3; for(int i=1;i<=n;i++) { for(int k=n-1;k>=i;k--) { System.out.print(" "); } for(int j=1;j<=2*i-1;j++)//打印* {

java 上机练习题

上机练习一 一、将Vehicle 和VehicleDriver两个文件用自己的文本编辑器重新编辑并编译和运行,掌握类和对象的定义和使用 1、V ehicle.java (注意:以下代码有几个错误的地方,需要同学自己把他们找出来并更正过来) public class Vehicle{ public float journey; public int wheelNum; public int loadNum; public int driveSpeed; /** *Vehicle 类构造函数,设定初始值 */ public Vehicle(){ journey=100.3f; wheelNum=4; loadNum=1; } /** *Vehicle类的driveAt行驶方法 */ public void driveAt(int speed){ if (speed>=60){ System.out.println("行车速度太快,容易造成事故"); //如果要求的车速太快,则机动车自动以40单位速度行驶 driveSpeed=40; } else {

System.out.println("你在安全行驶速度内行驶"); driveSpeed=speed; } } } 2、V ehicleDriver.java public class VehicleDriver{ public String name; //定义司机的名字 /** *VehicleDriver 类构造函数 */ public VehicleDriver(){ name="TOM"; } /** *VehicleDriver 类对象的work方法 */ public void work(){ Vehicle v=new Vehicle(); //生成Vehicle类的对象v v.driveAt(70); //调用v对象所固有的driveAt()方法 } public static void main(String args[]){ //生成VehicleDriver类的对象vb VehicleDriver vd=new VehicleDriver(); vd.work(); //调用vd对象所固有的work()方法

Java程序设计上机实验

班级号一学号_姓名一题号java(多文件应压缩为rar): 实验1:熟悉上机环境,编写并运行简单的java程序(3学时)实验目的 (1)熟悉Java程序开发环境J2SDK+JCreator的安装及使用 ⑵熟悉Java Application 和Applet程序的结构及开发步骤 ⑶熟练掌握if语句的使用 ⑷掌握Math.sqrt()等常用数学函数的用法 ⑸熟悉System.out.print()的用法 实验内容及要求 按Java Application 和Applet两种方式分别编写程序,求 一元二次方程ax2+bx+c=0的根(系数在程序中给定),并输出。 思考并验证 (1)分别给定以下几组系数,给出输出结果 a=1,b=5,c=3 a=4, b=4, c=1 a=2, b=3, c=2 : + i ________ +_ _______ i ⑵如果程序的public类的类名和源文件的文件名不一样会有什

么问题? (3) 将类的public 修饰去掉是否可行?接着再将类名换为其它是 否可行?这说明了什么? (4) 将程序中main 前面的public 去掉,重新编译执行你的程序,你看到 了什么信息? (5) 将程序中main 前面的static 去掉,重新编译执行你的程序,你看到 了什么信息?为什么? (6) 本次上机中,你还遇到了什么问题,是如何解决的?

班级号一学号_姓名一题号java (多文件应压缩为rar ): 实验 2:控制流程 1(3 学时 ) 实验目的 (1) 进一步熟悉使用 if 语句 (2) 掌握循环语句实现循环的方法 实验内容及要求 输出时,只使用下面的语句: System.out.print( “ ”); // 不换行 System.out.print( “* ”); // 并且不换行 System.out.print( “+”); // 并且不换行 System.out.println( “*”;) // 并换行 编写程序输出(注:在图形的中心处有一个加号 ' +'): 思考并验证 下面程序片段给出了从键盘输入一个整数的方法: import java.io.*; 输出一个空格, 并且 输出一个字符' * ', 输出一个字符' +', 输出一个

西电计算机Java上机实验题目

Java课程上机练习题 一、J ava语言基础 实验目标: 掌握Java语法;掌握Java程序结构;掌握Java编译、调试、运行的方法。实验要求: 编写一个程序,程序提供两种功能: 1.用户输入一个整数,程序计算并输出从1开始到该整数的所有整数之和; 同时,计算并输出不大于该整数的所有素数的数目。 2.用户输入一个数字串,程序判断该数字串各位上数字的奇偶性,并分别输出奇、偶数位的计数值及各位的加和值。 程序应具有良好的人机交互性能,即:程序应向用户提示功能说明,并可根据用户的功能选择,执行对应的功能,并给出带详细描述信息的最终执行结果。 二、J ava的面向对象特性 实验目标: 掌握面向对象的编程方法;掌握Java的面向对象特性;掌握采用面向对象技术构建系统的一般方法。 实验要求: 编写一个程序,程序提供对图形的绘制功能(模拟绘制,采用文本输出的形式表现绘制内容): 1.构建所有图形的父类:Shape,该类中定义图形的基本属性及方法。 2.构建基本图形类:矩形(Rectangle)、圆(Circle)、正三角形(Triangle)。 3.可通过多态实现对任意图形的绘制。 4.定义静态方法,该方法可以对传入的对象实例进行判断,并输出该对象实例的类型。 5.定义静态方法,该方法可以输出传入的对象实例的中心点坐标。

6.构建测试类,该类实现与用户的交互,向用户提示操作信息,并接收用户的操作请求。 程序应具有良好的类层次结构,良好的人机交互性能,即:程序应向用户提示功能说明,并可根据用户的功能选择,执行对应的功能,并给出带详细描述信息的最终执行结果。 三、J ava的高级语言特征 实验目标: 熟悉Java的泛型;了解Java的泛型特点;初步掌握Java的泛型编程方法。实验要求: 编写一个程序,程序提供记事本功能: 1.构建记事本类,该类能存储不定数量的记录;能获得已经存储的记录数量;能追加记录;能展示已经存储的全部记录或其中任何一条记录;能删除已经存储的全部记 录或其中任何一条记录。 2.构建测试类,该类实现与用户的交互,向用户提示操作信息,并接收用户的操作请求。 程序应具有良好的人机交互性能,即:程序应向用户提示功能说明,并可根据用户的功能选择,执行对应的功能,并给出带详细描述信息的最终执行结果。 四、J ava的输入输出 实验目标: 掌握Java输入输出类;掌握Java输入输出特点;掌握Java输入输出编程方法。 实验要求: 编写一个程序,程序实现对用户指定的文本文件中的英文字符和字符串的个数进行统计的功能,并将结果根据用户选择输出至结果文件或屏幕。 1.构建统计类,该类实现对I/O的操纵;实现对文本文件中英文字符、字符串的统计;实现对统计结果的输出。 2.构建测试类,该类实现与用户的交互,向用户提示操作信息,并接收用

实验二 Java类-实验报告

南京信息工程大学实验(实习)报告 实验(实习)名称Java类实验(实习)日期 10.17 得分指导教师刘文杰院计算机与软件学院专业软件工程年级 2017级班次 1 姓名张成学号20171344024 1.实验目的: 1)熟练MyEclipse工具的使用与调试; 2)掌握Java类、方法和变量的定义和使用; 3)熟悉方法重载和覆盖、掌握this和supper关键字使用; 4)掌握4类访问控制符的使用。 2.实验内容: (1)定义一个类Circle,实现其面积计算功能getArea(); (2)编写程序,读入一个正整数并按降序显示它的所有最小因子。(教材第3章习题9)(3)利用多态性编程,实现求三角形、正方形和圆形的面积。(教材第4章习题6) 3.实验步骤 1、 public class Circle { public double radius; public Circle(double r) { radius= r; } public double getArea() { return radius*radius*Math.PI; } public static void main(String[] args) { Circle area1 = new Circle(5); System.out.println("The area is " + area1.getArea()); } }

2、 import java.util.Scanner; public class Read { public static void main(String[] args) { Scanner input =new Scanner(System.in); System.out.print("输入一个正整数:"); int n=input.nextInt(); int []a=new int[n]; int []b=new int[n]; int p,q=0,m=0; for(p=2;p<=n;p++) { while(n%p==0) { n=n/p; if(n!=1) { a[q]=p; q++; } else { a[q]=p; } } } while(q!=-1) { b[m]=a[q]; m++; q--; } for(p=0;p

JAVA实验6答案

广东海洋大学学生实验报告书(学生用表) 实验名称实验六. Java的接口与实现课程名称Java程序设计与开发 技术 课程号16232204 学院(系) 信息学院专业计算机科学与技术班级计科 学生姓名学号实验地点钟海楼 04019 实验日期 2015年 10月26日 一、实验目的 (1)学习掌握Java中类怎样实现接口、接口回调技术; (2)学习掌握Java 程序中面向接口的编程思想。 二、实验任务 完成实验六指导上实验1、实验2、实验3的实验任务。 三、实验仪器设备和材料 安装有J2SE开发工具的PC机。 四、实验内容和步骤 实验1 代码如下: Estimator.java interface CompurerAverage{ public double average(double x[]); } class Gymnastics implements CompurerAverage{ public double average(double x[]){ int count=x.length; double aver=0,temp=0; for(int i=0;i

for(int i=1;i2) aver=aver/(count-2); else aver=0; return aver; } } class School implements CompurerAverage{ public double average(double[] x){ int count=x.length; double sum=0; for(int i=0;i

JAVA上机实验参考

《JAVA上机实验参考》 目录 实验一JDK开发工具 (1) 向生成的源文件中添加代码 (4) 编译并运行程序 (5) 构建并部署应用程序 (6) 实验二Java语言基础 (7) 实验三控制语句 (10) 实验四类与对象 (11) 实验五接口、包与泛型 (12) 实验六字符串处理 (16) 实验七异常处理 (18) 实验八输入与输出处理 (21) 实验九多线程 (23) 实验十Applet (25) 实验十一Swing图形界面设计 (28) 实验一JDK开发工具 一、实验目的 1.熟悉JDK开发环境。 2.熟悉Netbeans IDE的使用。 二、实验内容 要学完本教程,您需要具备以下软件和资源。 软件或资源要求的版本 NetBeans IDE版本7.2、7.3、7.4 或8.0 Java 开发工具包(JDK)版本6、7 或8

设置项目 要创建IDE 项目,请执行以下操作: 1. 启动NetBeans IDE。 2. 在IDE 中,选择"File"(文件)> "New Project"(新建项目),如下图所示。 3. 在新建项目向导中,展开"Java" 类别,然后选择"Java Application"(Java 应用程序),如下图 所示。然后,单击"Next"(下一步)。

4. 在向导的"Name and Location"(名称和位置)页中,执行以下操作(如下图所示): ?在"Project Name"(项目名称)字段中,键入HelloWorldApp。 ?将"Use Dedicated Folder for Storing Libraries"(使用专用文件夹存储库)复选框保留为取消选中状态。 ?在"Create Main Class"(创建主类)字段中,键入helloworldapp.HelloWorldApp。 5. 单击"Finish"(完成)。 此时将创建项目并在IDE 中打开。此时,您应该看到以下组件:

JAVA第四版实验2实验报告

实验1 1.实验要求: 编写一个Java应用程序,该程序在命令行窗口输出希腊字母表。 2.实验内容: 3.实验分析: (1)将一个double型数据直接赋值给float型变量,程序编译时提示怎样的错误。 可能损失精度。 (2)在应用程序的main()方法中增加语句:float x=0.618,程序能编译通过吗? 不能通过编译,提示可能损失精度。 (3)在应用程序的main()方法中增加语句:byte b=128编译能通过吗?在应用程序的main()方法中增加语句:int z=(byte)128;程序输出变量z的值是多少? 增加byte b=128时编译不能通过,提示可能损失精度。 增加int z=(byte)128时结果如下所示。 实验2 1.实验要求: 编写一个Java应用程序,该程序在命令行窗口输出数组的引用以及元素的值。 2.实验内容:

3.实验分析: (1)在程序的【代码4】之后增加语句”a[3]=200;”,编译是否有错?运行是否有错? (2)在程序的【代码4】之前输出二维数组b的各个一维数组的长度和引用。

(3)在程序的【代码4】之后输出二维数组b的各个一维数组的长度和引用。

实验3 1.实验要求: 编写一个Java应用程序,输出数组a的全部元素,并将数组a的全部或部分元素复制到其他数组中,然后改变其他数组的元素的值,再输出数组a的全部元素。 2.实验内容: 3.实验分析:

(1)在程序的【代码4】之后增加语句:int []tom=Arrays.copyOf(c,6); System.out.println(Arrays.toString(tom)); (2)在程序的最后一个语句之后增加语句:int []jerry=Arrays.copyOf(d,1,8); System.out.println(Arrays.toString(jerry));

Java面向对象编程上机-练习题汇总

【练习题】类的成员变量: 猜数字游戏:一个类A有一个成员变量v,有一个初值100。定义一个类,对A 类的成员变量v进行猜。如果大了则提示大了,小了则提示小了。等于则提示猜测成功。 【练习题】类的成员变量: 请定义一个交通工具(Vehicle)的类,其中有: 属性:速度(speed),体积(size)等等 方法:移动(move()),设置速度(setSpeed(int speed)),加速speedUp(),减速speedDown()等等. 最后在测试类Vehicle中的main()中实例化一个交通工具对象,并通过方法给它初始化speed,size的值,并且通过打印出来。另外,调用加速,减速的方法对速度进行改变。 【练习题】类的成员变量与方法、构造方法 在程序中,经常要对时间进行操作,但是并没有时间类型的数据。那么,我们可以自己实现一个时间类,来满足程序中的需要。 定义名为MyTime的类,其中应有三个整型成员:时(hour),分(minute),秒(second),为了保证数据的安全性,这三个成员变量应声明为私有。 为MyTime类定义构造方法,以方便创建对象时初始化成员变量。 再定义diaplay方法,用于将时间信息打印出来。 为MyTime类添加以下方法: addSecond(int sec) addMinute(int min) addHour(int hou) subSecond(int sec) subMinute(int min) subHour(int hou) 分别对时、分、秒进行加减运算。 【练习题】构造方法 编写Java程序,模拟简单的计算器。 定义名为Number的类,其中有两个整型数据成员n1和n2,应声明为私有。编写构造方法,赋予n1和n2初始值,再为该类定义加(addition)、减(subtration)、乘(multiplication)、除(division)等公有成员方法,分别对两个成员变量执行加、减、乘、除的运算。 在main方法中创建Number类的对象,调用各个方法,并显示计算结果。 【练习题】构造方法: 编写Java程序,用于显示人的姓名和年龄。 定义一个人类(Person),该类中应该有两个私有属性,姓名(name)和年龄(age)。定义构造方法,用来初始化数据成员。再定义显示(display)方法,将姓名和年龄打印出来。

Java上机实验-类的使用

实验名称Java上机实验二 姓名:山水不言学号:xxxxxx 一、实验内容 ○1编程创建一个Box类。要求:定义三个实例变量分别表示立方体的长、宽和高,定三个构造方法(必须包含一个无参构造方法,一个满参构造方法)对这3个变量进行初始化,然后定义一个方法求立方体的体积。创建一个对象,求给定尺寸的立方体的体积。 实验思路: 创建一个Box类,将它的长宽高以及体积实例变量设为private,类中声明一个求体积的public方法。设置三个构造函数来对者三个变量初始化: 1、构造函数有三个参数,分别对应实例的长、宽和高。构造函数 可以对变量赋值合法性进行判断。 2、构造函数有两个参数则对应实例的长和宽,高默认为1,构造 函数可以对函数合法性进行判断。 3、构造函数没有参数实例的长宽高默认为0 在另一个类里创建3个Box对象,调用volume函数分别求体积。 实验源代码: package com.box; public class box_demo { public static void main(String[] args) {

// TODO自动生成的方法存根 Box box1=new Box(); Box box2=new Box(12.3,34.1); Box box3=new Box(12.3,34.1,10.0); System.out.print("the volume of the box1:"+box1.volume()+"\n"); System.out.print("the volume of the box2:"+box2.volume()+"\n"); System.out.print("the volume of the box3:"+box3.volume()); } } package com.box; public class Box { private double height; private double width; private double length; private double volume; public Box() { this.height=0; this.length=0; this.width=0; } public Box(double Box_len,double Box_wid,double Box_height) { if(Box_len<0) this.length=0; else this.length=Box_len; if(Box_wid<0) this.width=0; else this.width=Box_wid; if(Box_height<0) this.height=0; else this.height=Box_height; } public Box(double Box_len,double Box_wid) {

参考_JAVA实验报告

实验报告 实验名称工资管理程序第 2 次实验实验日期 2009- - 指导教师 班级 04软件工程学号姓名成绩 一、实验目的 1、掌握类的定义、域的定义及方法的定义。 2、掌握对象的定义与使用 3、掌握抽象类的用法 二、实验内容 1、建立一个抽象类Employee类 至少包括成员变量: 名、姓、年龄、性别 至少包括构造函数: 名和姓作为参数 至少包括方法: 取名称 至少包括抽象方法: 取收入earnings() 重写Object的toString()方法,返回Employee类的描述信息如名称信息 2、建立老板类Boss类继承Employee类 至少构造函数以名和姓及周工资作为参数 老板的工资是周工资 3、建立销售人员类 销售人员的收入= 销售量* 单价 要求:每个销售人员对象都能知道当前共有多少个销售人员 ... ... 4、在main函数中,分别创建老板对象、销售人员对象 三、实验步骤 3.1 进入eclips,创建一个名为employ的工程,新建一个抽象类Employee类 类中的成员变量有private String firstname; private String lastname; private String sex; private String age; 构造函数为employee(){} //无参数的构造函数 employee(String fn,String ln) //以名和姓为参数的构造函数 { this.firstname=fn; https://www.doczj.com/doc/e915464696.html,stname=ln; } employee(String fn,String ln,String s,String a)//参数完整的构造函数 { this(fn,ln);

浙大JAVA实验题答案answer

实验8 Method的使用 1.程序填空题,不要改变与输入输出有关的语句。 50001 输入一个正整数repeat (0

《Java程序设计》上机实验

实验 1: 熟悉上机环境,编写并运行简单的java 程序( 3 学时) 实验目的 (1)熟悉 Java 程序开发环境 J2SDK+JCreator的安装及使用 (2)熟悉 Java Application 和 Applet 程序的结构及开发步骤 (3)熟练掌握 if 语句的使用 (4)掌握 Math.sqrt()等常用数学函数的用法 (5)熟悉 System.out.print()的用法 实验内容及要求 按Java Application 和 Applet 两种方式分别编写程序,求一元二次方程 ax2+bx+c=0 的根(系数在程序中给定),并输出。 思考并验证 (1)分别给定以下几组系数,给出输出结果a=1, b=5, c=3 a=4, b=4, c=1 a=2, b=3, c=2:+ i + i (2)如果程序的 public 类的类名和源文件的文件名不一样会有什么问题? (3)将类的 public 修饰去掉是否可行?接着再将类名换为其它是否可行?这说明了什么 ? (4)将程序中 main 前面的 public 去掉,重新编译执行你的程序,你看到了什么信息? (5)将程序中 main 前面的 static 去掉,重新编译执行你的程序,你看到了什么信息?为 什么? (6)本次上机中,你还遇到了什么问题,是如何解决的? 第1 页

实验 2:控制流程1(3 学时 ) 实验目的 (1)进一步熟悉使用 if 语句 (2)掌握循环语句实现循环的方法 实验内容及要求 输出时,只使用下面的语句: System.out.print(“”); //输出一个空格,并且不换行System.out.print(“*”); //输出一个字符’*’,并且不换行System.out.print(“+”); //输出一个字符’+’,并且不换行System.out.println(“*”;) // 输出一个字符’*’,并换行 编写程序输出(注:在图形的中心处有一个加号’+’): * * * * ***** ***+*** ***** * * * * 思考并验证 下面程序片段给出了从键盘输入一个整数的方法: import java.io.*; InputStreamReader ir; BufferedReader in; ir=new InputStreamReader(System.in); in=new BufferedReader (ir); try {String s=in.readLine(); int i=Integer.parseInt(s);//转换成整形

相关主题
文本预览
相关文档 最新文档