所以我是Stack Overflow的新手,希望我正确地说出这个问题。 我从课堂上得到了这个任务,并且完成了它,直到我的教授调整了一点任务。总而言之,我创建了2个类,它们可以相互协作,并将变量从另一个类调用到它被调用的类中。现在我的教授想要一个java文件,这意味着一个类文件。我不知道如何用两个代码将程序重写为一个类。
分配:
“(Location类)设计一个名为Location的类,用于在二维数组中定位最大值及其位置。该类包含存储最大值及其索引的公共数据字段row,column和maxValue。一个二维数组,其中row和column为int类型,maxValue为double类型。 编写以下方法,返回二维数组中最大元素的位置:
public static Location locateLargest(double [] [] a)
返回值是Location的实例。编写一个测试程序,提示用户输入二维数组并显示数组中最大元素的位置。这是样本运行:
输入数组的行数和列数:3 4 输入数组: 23.5 35 2 10 4.5 3 45 3.5 35 44 5.5 9.6 最大元素的位置在(1,2)
处为45
所以我用第一类编码完成了所有这些:
public class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}
然后是在第二课程中调用程序的代码
import java.util .*;
public class TestLocation {
public static void main(String[] args)
{
Location mylocation;
int row;
int column;
double [][] numArray; //we can leave this blank
Scanner Reading = new Scanner(System.in);
System.out.println(" How many rows will you be entering?");
row = Reading.nextInt(); //nextInt -what it reads will convert into a integer
System.out.println(" How many columns will you be entering?");
column = Reading.nextInt();
numArray = new double [row][column];
System.out.println("Enter the array please");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
numArray[i][j] = Reading.nextDouble();
//i is the row and j is the column
}
}
mylocation = locateLargest(numArray);
int temp = (int)mylocation.maxValue; //this is to print out the difference between int and double(decimal)
if (temp == mylocation.maxValue)
System.out.println("Highest Number: " +(int)mylocation.maxValue); //(int forces to be an integer then the double it was, eliminate decimal places)
else
System.out.println("Highest Number: " +mylocation.maxValue); //print out with decimal
System.out.println("Position: (" + mylocation.row+", " + mylocation.column +")");
Reading.close();
}
public static Location locateLargest(double[][] a)
{
Location mylocation = new Location(); //this is where we are going to store my information in
mylocation.maxValue = a[0][0]; //this is the max value to the first number
mylocation.row = 0;
mylocation.column = 0;
for (int i = 0; i < a.length; i++) //Length of the row; how many row there are
{
for (int j = 0; j < a[0].length; j++) //Length of a row; how many column in that row
//we added array here in the second because we want of get the length of the second dimension
//.length get the length of the current dimension , so a.length get the length of the first dimension
{
if (mylocation.maxValue < a[i][j] )
{
mylocation.maxValue = a[i][j];
mylocation.row = i;
mylocation.column = j;
}
}
}
return mylocation;
}
}
如何使用上面的赋值框中的新指令重新编程,这需要我将所有编码转换为一个class = 1 java文件?我几乎尝试了一切而无法得到我想要的结果。
答案 0 :(得分:1)
一个java文件只允许一个公共类文件。从第一个java文件中删除public关键字,并将它们放在同一个文件中,第二个文件将起作用。
class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}