此getsize方法要求数字在方矩阵中为空白。输入后,它将返回新矩阵。我想在do-while循环中检查这些值。我添加了完整的代码。如果要输入的值之一出现多次,我想打印出来,然后选择将矩阵中的该点更改为新数字。
import java.util.Scanner;
公共课广场{
private int [][]matrixblank;
private int firstrow;
private int number;
private int count;
public square() {
matrixblank=getsize();
firstrow=0;
number=0;
count=0;
}
public int [][]getsize() {
int rows=0;
int f=0;
Scanner size = new Scanner(System.in);
//THIS SETS SIZE OF THE MATRIX
System.out.println("How big do you want your magic square?");
rows=size.nextInt();
while(rows<1){
System.out.println("Enter an accepted value of the size of your magic square");
rows=size.nextInt();}
// END OF SETTING MATRIX
// FINDS VALUE OF THE NUMBERS IN THE MATRIX
int matrix[][]= new int [rows][rows];
for(int row=0; row<matrix.length;row++){
for(int column=0;column<matrix[row].length;column++){
System.out.println("Enter value for"+ row + " "+ column);
f=size.nextInt();
matrix[row][column]=f;
//END OF FINDING VALUES
//CHECKS TO SEE IF THE VALUE IS TOO BRING OR SMALL
while(f<1||f>matrix.length*matrix.length){
System.out.println("This number is too big or small please. Enter a new Number.");
f=size.nextInt();
matrix[row][column]=f;
}
//END OF CHECKING IF THE VALUE IS IN BOUNDS
if(matrix[row][column]==f){
System.out.println("Enter a new number that hasnt been entered before");
f=size.nextInt();
matrix[row][column]=f;
}
}}
return matrix;
}
public void sumoffirstrow() {
for(int firstrow1=0;firstrow1<matrixblank[0].length;firstrow1++) {
firstrow+=matrixblank[0][firstrow1];
number=firstrow;
}
}
public boolean checkrows(){
int sumrows=0;
for(int a=0;a<matrixblank.length;a++){
sumrows=0;
for(int b=0;b<matrixblank.length;b++){
sumrows+=matrixblank[a][b];
}
if(sumrows!=number){
return false;
}
}
return true;
}
public boolean checkcolumns(){
int sumcolumns=0;
for(int c =0; c < matrixblank.length; c++){
sumcolumns = 0;
for(int d = 0; d< matrixblank.length; d++){
sumcolumns += matrixblank[d][c];
}
if(sumcolumns != number){
return false;
}
}
return true;
}
public boolean TLBR(){
int sumofLtoR;
sumofLtoR=0;
for(int e=0;e<matrixblank.length;e++){
sumofLtoR+=matrixblank[e][e];
}
if(sumofLtoR!=number){
return false;
}
return true;
}
public boolean TRBL(){
int sumofRtoL;
sumofRtoL=0;
for(int f=0;f<matrixblank.length;f++){
sumofRtoL+=matrixblank[f][matrixblank.length-1-f];
}
if(sumofRtoL!=number){
return false;
}
return true;
}
public String getnumbers() {
String b = "";
for(int i = 0; i < matrixblank.length; i++){
b +="\n";
for(int j = 0; j < matrixblank[0].length; j++){
b += " " + matrixblank[i][j];
}
}
return b;
}
public String toString() {
if(checkrows()&&checkcolumns()&&TLBR()&&TRBL()){
return "This is a magic square"+getnumbers();
}
else{
return "This is not a magic square\n"+getnumbers();
}
}
}