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

Java入门编程(作业)Time3实现总结(二)

2016-03-26 22:51 495 查看
  题目很简单:求一个二维数组的鞍点(行中最大且列中最小的那个元素)。先附上成果:

import java.util.Scanner;
public class Point{
public static void main(String[] args){
int rows = 0, length = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the length:");
length = scanner.nextInt();
System.out.print("Please enter the rowss:");
rows = scanner.nextInt();
Element[][] array = new Element[rows][length];
System.out.print("Please enter the elements of the array:\n");
for (int countR = 0; countR < rows; countR++){
for (int countL = 0; countL < length; countL++){
int a = scanner.nextInt();
array[countR][countL] = new Element(a);
}
}
for (int countR = 0; countR < rows; countR++){
FindBIL(array, length, countR);
}
for (int countL = 0; countL < length; countL++){
FindLIR(array, countL, rows);
}
for (int countR = 0; countR < rows; countR++){
for (int countL = 0; countL < length; countL++){
array[countR][countL].getresult();
if (array[countR][countL].Cheak)
System.out.print(array[countR][countL].number+"is the point");
}
}
}
static void FindBIL(Element[][] ar, int length, int row){
int sign = 0;
for (int count = 1; count < length; count++){
if (ar[row][count].number > ar[row][sign].number)
sign = count;
}
ar[row][sign].ChangeBIL();
}
static void FindLIR(Element[][] ar, int length, int rows){
int sign = 0;
for (int count = 1; count < rows; count++){
if (ar[count][length].number < ar[sign][length].number)
sign = count;
}
ar[sign][length].ChangeLIR();
}
}

class Element{
private boolean BIL = false;
private boolean LIR = false;
int number;
public boolean Cheak = false;
public Element(int a){
this.number = a;
}
void ChangeBIL(){
this.BIL = true;
}
void ChangeLIR(){
this.LIR = true;
}
void getresult(){
if (BIL && LIR)
this.Cheak = true;
}
}
  开始时我希望能做的尽量完善一点,可以实现一个任意加长的数组,查了资料后发现这是不可能的,除非使用容器,但那个涉及到泛型的知识,鉴于时间较短不能也不想提前深入研究,所以放弃了这个想法。退而求其次,使用可变数组(VLA),让用户输入决定数组的大小,这样其实也不错,增加了适当的交互性。

  至于算法,我的想法是创建一个对象数组,对象的类中有一些基本的属性如该位置储存的数字等,还有一些特殊的,比如是否是该行中最大的数,是否是该列中最小的数,是否是鞍点的属性。这样,就可以把“寻找鞍点”和“输出鞍点”这两件事分的很清楚,可以使结构更清楚。

  在主类中还定义了两个方法,分别是找出行中最大元素和列中最小元素并改变其属性。这样三次遍历后就可以完全结束任务。

  这次编程最主要的收获不是语法上的,而是对java的认识。面向对象编程相对于面向过程编程来说,可以更加清晰的表达出“结构”的理念,每个类可以承担的任务和属性相对于基本数据类型来说要多的多,可表达的信息也更多更清晰。

  当然,还有另一个收获,是在课堂上获得的:this.加不加并不是没有区别的。当存在局部变量和类变量(成员变量)时,方法中的局部变量会默认的盖掉类变量,而使用this.则可以强制在方法中使用类变量。

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