Search code examples
if-statementmultidimensional-arrayduplicatesdo-whilemagic-square

Disable duplication of numbers in an array


I managed to make the program works but the problem is the between Row 3 Column 2 and Row 3 Column 3. Whenever i input two duplicate numbers in row 3 column 2 and row 3 column 3, it accepts those two. If i input 1 there, it loops back. My only problem is the number 8. Why's that?

Here's my code:

Scanner input = new Scanner(System.in);
    int magic_square[][]=new int[3][3];
    int counter = 0;
    int valid = 0;
    int duplicate = 0;
    int sum_row[] = new int[3];
    int sum_col[] = new int[3];
    int rowcolcheck =0;
    int rowcheck=0;

    System.out.println("Enter the Magic Number: ");
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            valid = 0;
            do{
                duplicate = 0;
                System.out.print("Row "+(i+1)+" Column "+(j+1)+": ");
                magic_square[i][j] = input.nextInt();
                if(magic_square[i][j]<0||magic_square[i][j]>9){
                    System.out.println("Invalid input range! Please try again!");
                    valid = 1;
                    continue;
                }

                valid = 0;
                for(int a=0;a<3;a++){
                    for(int b=0;b<3;b++){
                        if(a==i&&b==j)
                        {
                            continue;
                        }
                        if(magic_square[i][j]==magic_square[a][b]){
                            duplicate = 1;
                            System.out.println("Duplicate Number! Please try again!");
                            continue;
                        }
                        if(duplicate==1){
                            valid = 1;
                        }

                    }
                }
            }while(valid!=0);
        }
    }

Sample output


Solution

  • I fixed it!

     valid = 0;
                for(int a=0;a<3;a++){
                    for(int b=0;b<3;b++){
                        if(a==i&&b==j)
                        {
                            continue;
                        }
                        if(magic_square[i][j]==magic_square[a][b]){
                            valid = 1; // i change this. it was duplicate = 1. 
                                       //now it's valid = 1.
                            System.out.println("Duplicate Number! Please try again!");
                            continue;
                        }
                          //i removed this conditon and the integer duplicate =
                          //                      0 and it works like a charm!
                        //if(duplicate==1){
                          //  valid = 1;
                        //}
    
                    }
                }