日期:2014-05-20 浏览次数:20829 次
import java.util.Scanner;
public class Test {
static class Location{
int row,col;
double max;
public Location(int row,int col,double max){
this.row = row;
this.col = col;
this.max = max;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public double getMax() {
return max;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double[][] arr = null;
try {
System.out.println("Enter the number of rows and columns of the array:");
String input = scanner.next();
int row = Integer.valueOf(input);
input = scanner.next();
int col = Integer.valueOf(input);
arr = new double[row][col];
System.out.println("enter the array");
for(int i = 0;i < row;i++){
for(int j = 0;j < col;j++){
input = scanner.next();
arr[i][j] = Double.valueOf(input);
}
}
} catch (Exception e) {
System.out.println("input error");
}
Location location = locationLargest(arr);
System.out.println("The location of the largest element is " +
location.getMax() + " at (" + (location.getRow() + 1) + "," +
(location.getCol() + 1) + ")");
}
static Location locationLargest(double[][] a){
Location location = new Location(0,0,a[0][0]);
for(int i = 0;i < a.length;i++){
for(int j = 0;j < a[0].length;j++){
if(a[i][j] > location.getMax()){
location = new Location(i,j,a[i][j]);
}
}
}
return location;
}
}
------解决方案--------------------
import java.util.Scanner;
public class TestSync {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int countX = 0, countY = 0;
double[][] data = null;
for (;;) {
System.out
.print("Enter the number of rows and columns of the array:");
String str = s.nextLine();
try {
String[] temp = str.split("\\s+");
data = new double[Integer.valueOf(temp[0])][Integer
.valueOf(temp[1])];
} catch (Exception e) {
continue;
}
break;
}
countX = data.length;
countY = data[0].length;
double max = Double.MIN_NORMAL;
int maxIndexX = -1;
int maxIndexY = -1;
boolean exitFlag = false;
while (!exitFlag) {
System.out.println("Enter the array:");
exitFlag = true;
for (int index = 0; index < countX * countY; index++) {
try {
data[index / countY][index % countY] = s.nextDouble();
if (max < data[index / countY][index % countY]) {
maxIndexX = index / countY;
maxIndexY = index % countY;
max = data[index / countY][index % countY];
}
} catch (Exception e) {
exitFlag = false;
break;
}
}
}
System.out.println("The location of the largest element is " + max
+ " at ( " + maxIndexX + "," + maxIndexY + ")");
}
}