Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Original lab 3 text
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- int magicSquare[][] = new int[4][4];
- int i, j, x, y;
- int total;
- int getNum;
- boolean valid = true;
- Scanner obj = new Scanner(System.in);
- //User Enters values into array, second set of nested loops
- // checks if the value is in the required range and not duplicating
- for (i = 0; i < 4; i++) {
- for (j = 0; j < 4; j++) {
- while (valid) {
- System.out.println("Please fill in element: " + i + " " + j);
- getNum = obj.nextInt();
- for (x = 0; x < 4; x++) {
- for (y = 0; y < 4; y++) {
- if (magicSquare[x][y] = getNum;valid = false){
- if (valid) (magicSquare[i][j] = getNum )
- }
- }
- }
- }
- }
- }
- /*
- for ( i = 0; i < 4; i++) {
- for ( j = 0; j < 4; j++) {
- while (true){
- System.out.println("Please fill in element: " + i + " " + j);
- magicSquare[i][j] = obj.nextInt();
- for (x=0; x<4; x++){
- for(y=0;y<4;y++){
- if magicSquare[x][y] = magicSquare,
- checkNum = magicSquare[i][j];
- if (checkNum < 1 || checkNum > 16)
- if magicSquare[x][y] = checkNum, valid = false
- if(valid) magicSquare[i][j]=checkNum
- }
- }
- }
- }
- }
- }
- this was just another Idea i was messing around with, I'm confused with the logic, haven't been able to compile :(
- */
- //Magic Square must = 34 in all directions
- //Math check
- // Find and check the sum for each row.
- for (i = 0; i < 4; i++) {
- total = 0;
- for (j = 0; j < 4; j++)
- total += magicSquare[i][j];
- if (total != 34)
- System.out.println("Rows are not magical!");
- }
- // Find and check the sum for each column.
- for (j = 0; j < 4; j++) {
- total = 0;
- for (i = 0; i < 4; i++)
- total += magicSquare[i][j];
- }
- // Check diagonals
- if (magicSquare[0][0] + magicSquare[1][1] + magicSquare[2][2] + magicSquare[3][3] != 34)
- System.out.println("Diagonal Down is not magical!");
- if (magicSquare[3][0] + magicSquare[2][1] + magicSquare[1][2] + magicSquare[0][3] != 34)
- System.out.println("Diagonal up is not magical!");
- //Print out 2D array 'magicalSquare'
- for (i = 0; i < 4; i++) {
- for (j = 0; j < 4; j++) {
- System.out.print(magicSquare[i][j] + "\t");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement