gpt4 book ai didi

java - 我正在尝试这个简单的数独

转载 作者:太空宇宙 更新时间:2023-11-04 12:23:17 29 4
gpt4 key购买 nike

I am trying a simple sudoku program. i started by taking the values in a 3D array and then copied them into a 1D array by using mr.serpardum's method. i know that there is an error at the point where i am trying to find
duplicate elements,because even if i give same numbers as input the output says "its a sudoku" but i can't to find it...apparently i can't add any image coz i dont have enough credits

    public class SecondAssignment {
@SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
int i = 0, j = 0, k = 0;
boolean result = false;
int arr1[][];
arr1 = new int[3][3];
int arr2[];
arr2 = new int[9];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements in the sudoku block");
//getting elements into array
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr1[i][j] = Integer.parseInt(br.readLine());
}
}
//printing it in matrix form
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.print(arr1[i][j] + "\t");
}
System.out.println(" ");
}
//copying array1 elements into array 2
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr2[i * 3 + j] = arr1[i][j];
}
}

//finding duplicate elements
for (i = 0; i < arr2.length; i++) {
for (int m = i + 1; m < arr2.length; m++) {
if (arr2[i] == (arr2[m])) {
System.out.println("Not a sudoku");
//result = true;
} else {
System.out.println("Its a sudoku");
//result = false;
}
}
}
}
}

最佳答案

您可以将代码更新为以下内容

//finding duplicate elements
for( i = 0; i < arr2.length; i++){
for(int m = i+1; m < arr2.length; m++){
if(arr2[i] == (arr2[m])){
result = true;
break;
}
}
}
if(result){
System.out.println("\nNot a sudoku");
}
else{
System.out.println("\nIts a sudoku");
}

您应该在找到匹配项后立即使用中断。此代码仅检查数组(大小为 9)中是否存在重复元素。

关于java - 我正在尝试这个简单的数独,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614698/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com