您的位置:首页 > 编程语言 > Java开发

一些课后实践about java

2015-10-31 13:55 357 查看
代码1:

/*
* 设计一个矩形类,给定长和宽,输出它的面积和周长
*/

import java.util.*;
import java.util.Scanner;
public class Re
{
public static void main(String[] args)
{
Rectangle rectangle1 = new Rectangle();
System.out.println("The width is:"+rectangle1.width+",the width is:"+rectangle1.height+",the area is:"+rectangle1.getArea()+",the perimeter is:"+rectangle1.getPerimeter());
Rectangle rectangle2 = new Rectangle(4,40);
System.out.println("The width is:"+rectangle2.width+",the width is:"+rectangle2.height+",the area is:"+rectangle2.getArea()+",the perimeter is:"+rectangle2.getPerimeter());
Rectangle rectangle3 = new Rectangle(3.5,35.9);
System.out.println("The width is:"+rectangle3.width+",the width is:"+rectangle3.height+",the area is:"+rectangle3.getArea()+",the perimeter is:"+rectangle3.getPerimeter());
}
}

class Rectangle//功能函数,供主函数调用
{
double width,height;
Rectangle()
{
width=height=1.0;
}
Rectangle(double W,double H)
{
width= W;
height=H;
}
double getArea()//面积 计算
{
return width*height;
}
double getPerimeter()//周长计算
{
return 2*(width+height);
}
}


运行结果:

The width is:1.0,the width is:1.0,the area is:1.0,the perimeter is:4.0

The width is:4.0,the width is:40.0,the area is:160.0,the perimeter is:88.0

The width is:3.5,the width is:35.9,the area is:125.64999999999999,the perimeter is:78.8

代码2:

/*问题描述:设计一个位置类。
*程序输入:二维数组。
*程序输出:数组中的最大值及其位置。
*/
import java.util.*;
import java.util.Scanner;
class Location  //获取数组最大值的功能函数
{
int row,column;
double maxValue;
public void setRow(int i)
{
row=i;
}
public void setColumn(int j)
{
column=j;
}
public int getRow()
{
return row;
}
public int getColumn()
{
return column;
}
}

public class Max
{
public static Location locateLargest(double [][]a)
{
Location l=new Location();
l.maxValue=a[0][0];
l.setRow(0);
l.setColumn(0);
int i,j;
for(i=0; i<a.length; i++)
for(j=0; j<a[i].length; j++)
if(a[i][j]>l.maxValue)
{
l.maxValue=a[i][j];//依次每行每列比较,扫出最大值
l.setRow(i); //获取最大值所在的行列号数
l.setColumn(j);
}
return l;
}
public static void main(String[] args)
{
Max location1=new Max();
Location location2=new Location();
System.out.print("Enter the number of rows and columns of the array:");
Scanner in=new Scanner(System.in);
int m=in.nextInt();
int n=in.nextInt();
double [][]a=new double [m]
;
System.out.println("Enter the array:");
int i,j;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
a[i][j]=in.nextDouble(); //输入一个m行n列的数组序列

location2 =location1.locateLargest(a);//用location2保存函数返回的数组最大值信息
System.out.println("The location of the largest element is "+location2.maxValue+" at ("+location2.getRow()+","+location2.getColumn()+")");
}
}


运行结果:

Enter the number of rows and columns of the array: 3 4

Enter the array:

4 5 6 8

14 2 6 9

20 2 7 10

The location of the largest element is 20.0 at (2,0)


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: