Link to home
Start Free TrialLog in
Avatar of Kody-Burg
Kody-BurgFlag for United States of America

asked on

Java Program Infinate Loop

Hello everyone,

I am new to the java programming world, with only a few months of experience. I am writing a magic square program. A magic square is a N x N matrix of numbers in which every number from 1 to N2 must appear just once, and every row, column, and diagonal must add up to the same total. In my case, I am using a 3X3 matrix of numbers. Since it is a 3X3 matrix, I want to restrict the sum for all rows, columns, and diagonals to be 15.

When I run the check to see if the input forms a magic square, I get stuck in an infinate loop. Can someone help me figure out why this is happening and how to make this code work?

Thanks,

Kody

My source for MagicSquare.java

 
import java.util.Scanner;

import javax.swing.JTextField;

public class MagicSquare 
{
	static int magic_square[][] = new int[3][3];
	static int sum[] = new int[6];
	static Scanner keyboard = new Scanner(System.in);

	public static void main(String[] args)
	{
		//checkSquare();
	}
	
	static boolean count()
	{
		boolean all15 = true;
		sum[0] = magic_square[0][0] + magic_square[0][1] + magic_square[0][2];
		sum[1] = magic_square[1][0] + magic_square[1][1] + magic_square[1][2];
		sum[2] = magic_square[2][0] + magic_square[2][1] + magic_square[2][2];
		sum[3] = magic_square[0][0] + magic_square[1][0] + magic_square[2][0];
		sum[4] = magic_square[0][1] + magic_square[1][1] + magic_square[2][1];
		sum[5] = magic_square[0][2] + magic_square[1][2] + magic_square[2][2];
		
		for(int i = 0; i < 6; i++)
		{
			if(sum[i] != 15)
				all15 = false;
		}
		return all15;
	}
	
	static void printMagicSquare()
	{
		for(int i = 0; i < 3; i++)
		{
			System.out.println("********");
			System.out.println("*");
			for(int j = 0; j < 3; j++)
			{
				System.out.print(magic_square[i][j] + "*");
			}
			System.out.println(" " + sum[i]);
		}
		System.out.println("********");
		System.out.println(sum[3] + " " + sum[4] + " " + sum[5]);
	}
	
	static void checkSquare(int newValue, int row, int col)
	{
		int value = newValue;
		int i = row; 
		int j = col;
		
		while (true)
		{
		   // System.out.println();
		   // System.out.print("Row: ");
		   // i = keyboard.nextInt();
		   // System.out.print("Column: ");
		   // j = keyboard.nextInt();
		   // System.out.print("Value: ");
		   // value = keyboard.nextInt();
			if(value < 0 && i < 0 && j < 0)
			{
				System.out.println("Program Terminated!");
				break;
			}
			magic_square[i][j] = value;
			if(count())
			{
				System.out.println("Congratulations! You solved the magic square!");
				printMagicSquare();
				break;
			}
			printMagicSquare();
		}
		System.out.println("Game Over");
	}
}

Open in new window



My source for MagicSquareGUI.java

 
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MagicSquareGUI extends JFrame
									implements ActionListener
{
	private static final long serialVersionUID = 1L;
	
	JTextField[][] textField;
	JButton		   checkButton;
	JButton		   clearButton;
	JButton		   exitButton;
	JPanel 		   buttonPanel;
	MagicSquare	   newGame;
	
	public MagicSquareGUI()
	{
		super("MagicSquareGUI");
		JPanel panel = new JPanel(new GridLayout(3, 3));
		panel.setPreferredSize(new Dimension(250, 250));
		textField = new JTextField[3][3];
		
		for(int j = 0; j < 3; j++)
		{
			int k = j;
			
			for(int i = 0; i < 3; i++)
			{
				textField[i][j] = new JTextField();
				k++;
				panel.add(textField[i][j]);
			}
		}
		
		buttonPanel = new JPanel();

		checkButton = new JButton("Check");
		checkButton.addActionListener(this);
		
		clearButton = new JButton("Clear");
		clearButton.addActionListener(this);
		
		exitButton = new JButton("Exit");
		exitButton.addActionListener(this);
		
		buttonPanel.add(checkButton);
		buttonPanel.add(clearButton);
		buttonPanel.add(exitButton);
		
		add(panel, BorderLayout.WEST);
		add(buttonPanel, BorderLayout.EAST);
		
		newGame = new MagicSquare();
	}
	
	public static void main(String[] args)
	{
		MagicSquareGUI GUI = new MagicSquareGUI();
		GUI.setSize(475, 250);
		GUI.setVisible(true);
	}
	
	public void actionPerformed( ActionEvent e)
	{
	    if (e.getSource() == checkButton)
	    {
			for(int j = 0; j < 3; j++)
			{
				int k = j;
				
				for(int i = 0; i < 3; i++)
				{
					String newValue = textField[i][j].getText();
					int value = Integer.parseInt(newValue);
					MagicSquare.checkSquare(value, i, j);
					k++;
				}
			}
	    }
	    else if (e.getSource() == clearButton)
	    {
			for(int j = 0; j < 3; j++)
			{
				int k = j;
				
				for(int i = 0; i < 3; i++)
				{
					textField[i][j].setText("");
					k++;
				}
			}
	    }
	    else if (e.getSource() == exitButton)
	    {
	    	System.exit(0);
	    }
	}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Kody-Burg

ASKER

There is still an infinate loop after fixing that.
this looks ok to me, when do you get an infinite loop
import java.util.Scanner;

import javax.swing.JTextField;

public class MagicSquare 
{
	static int magic_square[][] = new int[3][3];
	static int sum[] = new int[6];
	static Scanner keyboard = new Scanner(System.in);

	public static void main(String[] args)
	{
		//checkSquare();
	}
	
	static boolean count()
	{
		boolean all15 = true;
		sum[0] = magic_square[0][0] + magic_square[0][1] + magic_square[0][2];
		sum[1] = magic_square[1][0] + magic_square[1][1] + magic_square[1][2];
		sum[2] = magic_square[2][0] + magic_square[2][1] + magic_square[2][2];
		sum[3] = magic_square[0][0] + magic_square[1][0] + magic_square[2][0];
		sum[4] = magic_square[0][1] + magic_square[1][1] + magic_square[2][1];
		sum[5] = magic_square[0][2] + magic_square[1][2] + magic_square[2][2];
		
		for(int i = 0; i < 6; i++)
		{
			if(sum[i] != 15)
				all15 = false;
		}
		return all15;
	}
	
	static void printMagicSquare()
	{
		for(int i = 0; i < 3; i++)
		{
			System.out.println("********");
			System.out.println("*");
			for(int j = 0; j < 3; j++)
			{
				System.out.print(magic_square[i][j] + "*");
			}
			System.out.println(" " + sum[i]);
		}
		System.out.println("********");
		System.out.println(sum[3] + " " + sum[4] + " " + sum[5]);
	}
	
	static void checkSquare(int newValue, int row, int col)
	{
		int value = newValue;
		int i = row; 
		int j = col;
		
			if(value < 0 && i < 0 && j < 0)
			{
				System.out.println("Program Terminated!");
				return;
			}
			magic_square[i][j] = value;
			if(count())
			{
				System.out.println("Congratulations! You solved the magic square!");
				printMagicSquare();
			}
			printMagicSquare();
	}
}

Open in new window

I answered the question
No, the existing program still isn't fully functional, and I no longer need to fix it. I posted a two-part question.
But if you never get count() true and your i and j called from the lops will never be
<0, so you'll never reach either of breaks' in your while(true) loop

Suppose they are not 15's when would you reach the end?
you asked how to fix the infinite loop and I showed you
It is beyond the scope of what is allowed on EE to "make it work"
You need to ask new specific questions if you find problems other than the infinite loop
I am re-requesting the deletion of this question. I requested a delete before, but an objection was posted. My new request states, with more detail, why I would like to delete the question.

Thank you for your participation.
you asked how to fix the infinite loop and I showed you
It is beyond the scope of what is allowed on EE to "make it work"
You need to ask new specific questions if you find problems other than the infinite loop

Am more than happy to help you with any other problems you find

Why do you go to checking if it is magic on the level of ecah cell?
You should firts assign all magic_squalre values and then go to check the square once.
Am I not right?

This works at least when it is not magic.
Give me the magic numbers and I;ll check if it works when it is magic

import java.util.Scanner;

import javax.swing.JTextField;

public class MagicSquare
{
	static int magic_square[][] = new int[3][3];
	static int sum[] = new int[6];
	static Scanner keyboard = new Scanner(System.in);

	public static void main(String[] args)
	{
		//checkSquare();
	}

	static boolean count()
	{
		boolean all15 = true;
		sum[0] = magic_square[0][0] + magic_square[0][1] + magic_square[0][2];
		sum[1] = magic_square[1][0] + magic_square[1][1] + magic_square[1][2];
		sum[2] = magic_square[2][0] + magic_square[2][1] + magic_square[2][2];
		sum[3] = magic_square[0][0] + magic_square[1][0] + magic_square[2][0];
		sum[4] = magic_square[0][1] + magic_square[1][1] + magic_square[2][1];
		sum[5] = magic_square[0][2] + magic_square[1][2] + magic_square[2][2];

		for(int i = 0; i < 6; i++)
		{
			if(sum[i] != 15) {
				return false;
            }
		}
		return true;
	}

    static void setValue(int i, int j, int value)  {
              magic_square[i][j] = value;
    }

	static void printMagicSquare()
	{
		for(int i = 0; i < 3; i++)
		{
			System.out.println("********");
			System.out.println("*");
			for(int j = 0; j < 3; j++)
			{
				System.out.print(magic_square[i][j] + "*");
			}
			System.out.println(" " + sum[i]);
		}
		System.out.println("********");
		System.out.println(sum[3] + " " + sum[4] + " " + sum[5]);
	}

	//static void checkSquare(int newValue, int row, int col)
            static void checkSquare()
	{
        /*
		int value = newValue;
		int i = row;
		int j = col;

		while (true)
		{
		   // System.out.println();
		   // System.out.print("Row: ");
		   // i = keyboard.nextInt();
		   // System.out.print("Column: ");
		   // j = keyboard.nextInt();
		   // System.out.print("Value: ");
		   // value = keyboard.nextInt();
			if(value < 0 && i < 0 && j < 0)
			{
				System.out.println("Program Terminated!");
				break;
			}
			magic_square[i][j] = value;
            */
			if(count())
			{
				System.out.println("Congratulations! You solved the magic square!");
				printMagicSquare();

			}  else
            {
                System.out.println("Not magic!");
			printMagicSquare();
            }
        System.out.println("Game Over");
		}

	}

Open in new window



import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MagicSquareGUI extends JFrame
									implements ActionListener
{
	private static final long serialVersionUID = 1L;

	JTextField[][] textField;
	JButton		   checkButton;
	JButton		   clearButton;
	JButton		   exitButton;
	JPanel 		   buttonPanel;
	MagicSquare	   newGame;

	public MagicSquareGUI()
	{
		super("MagicSquareGUI");
		JPanel panel = new JPanel(new GridLayout(3, 3));
		panel.setPreferredSize(new Dimension(250, 250));
		textField = new JTextField[3][3];

		for(int j = 0; j < 3; j++)
		{
			int k = j;

			for(int i = 0; i < 3; i++)
			{
				textField[i][j] = new JTextField();
				k++;
				panel.add(textField[i][j]);
			}
		}

		buttonPanel = new JPanel();

		checkButton = new JButton("Check");
		checkButton.addActionListener(this);

		clearButton = new JButton("Clear");
		clearButton.addActionListener(this);

		exitButton = new JButton("Exit");
		exitButton.addActionListener(this);

		buttonPanel.add(checkButton);
		buttonPanel.add(clearButton);
		buttonPanel.add(exitButton);

		add(panel, BorderLayout.WEST);
		add(buttonPanel, BorderLayout.EAST);

		newGame = new MagicSquare();
	}

	public static void main(String[] args)
	{
		MagicSquareGUI GUI = new MagicSquareGUI();
		GUI.setSize(475, 250);
		GUI.setVisible(true);
	}

	public void actionPerformed( ActionEvent e)
	{
	    if (e.getSource() == checkButton)
	    {
			for(int j = 0; j < 3; j++)
			{
				int k = j;

				for(int i = 0; i < 3; i++)
				{
					String newValue = textField[i][j].getText();
					int value = Integer.parseInt(newValue);
				//	MagicSquare.checkSquare(value, i, j);
                    MagicSquare.setValue(i, j, value);
					k++;
				}
			}
             MagicSquare.checkSquare();

	    }
	    else if (e.getSource() == clearButton)
	    {
			for(int j = 0; j < 3; j++)
			{
				int k = j;

				for(int i = 0; i < 3; i++)
				{
					textField[i][j].setText("");
					k++;
				}
			}
	    }
	    else if (e.getSource() == exitButton)
	    {
	    	System.exit(0);
	    }
	}
}

Open in new window

Why do you want to delete this question?
for_yan:

I have been trying to delete this question since before you made your first comment on it. I specified in multiple attempts to delete this question that I no longer needed a solution because I realized that I asked the question about a program project specs sheet that I misread, and at the time of the initial delete request, a valid solution had not yet been posted anyway. I was hoping that nobody would object so it would be deleted before I had multiple people posting possible solutions to the question so I could avoid this mess before it happened.

I appreciate your input.
I think there is no reason to delete - it is a valid question - we have dozens of them and this is even
more claer than many iother we have to deal with. Jusrt look at the code I poseted,try it with magic numbers
and if it does not work, we'll fix it.
modus_in_rebus,
please look attentively at this trail - the objection of objects in this case has no merit.
What objects posted was pretty trivial statement that while(true) may cause
infinite loop, but in fact there were several break; opertors inside - it was by no means
obvious why they don't break. I did follow up on the whole logic
and made this program much more sensible.

As to haveing one question and continuing to the next one - while that
is a bad practice in my opinon also- that happens with me all the time - after responding to
one question you have to follow and follow with the Asker someties for days.
And often someone else in the end "steals" your firsst solution.
So why only this question should be penalized for that?
Absolutely did not know anything.
When I finished figuring out with the program I first time saw that someone wants to delete it.
I don't even understand up to now who and wghy suggested to delete it
For me irt was quite legitinmate problem and only when I dfound the solution I saw some controversy, which still cannot understand now
what they are about
In my mind this is the question definitely not worse that doozens of others.
The Asker invested good effort - wrote something and asked
why it does not work.
 we found the falw in their logic and corrected it - most normal EE situation.
If we start deletyeing such questions we'll lose half of what we are doing
>For your information, the author first requested the deletion of this question after his post http:#a35488091. He then tried it again >afterwards, resulting in an objection each time.

How would I have known that? How do you know that? Who was objecting? Why he suddenly decided to delete it when he didn't receive any solution other than the trivial statement that infinite loop may be caused by while(true)...
All that time I was working with the code and brought this program to usable condition, and the Asker was happy with it.
Absolutely impossible to see the reason for revision of the Asker's decision.
How come objects could read  something that I could not see?

With all that strange happenings, the fundamental fact is I was helping the Asker,
I fixed the program. Asker happily used the program and was grateful and assigned points.
What is the reason for you to re-assaign points? No reason whatsoever.
I spent my time, I did useful job, Asker benefited from it. Return my points to me.



Where does this come from:

" I was approaching this project the wrong way, so I was writing the wrong code to start with. I no longer need a solution because it would not help me at all with the corrected view of this project at hand. Sorry to participating experts for the hassle."

How could I have seen it?


modus_in_rebus,

I see you conveniently deleted my comment that told for_yan that he posted the correct solution.

You also decided to finalize the question and award points to Objects' first two posts, which didn't solve the problem. You only re-opened the question 4 days ago (this is day 4, so technically 3 days ago and several hours) which is hardly enough time for me to check back in my busy work schedule. It's really sad that your post said 'which is a pity' that I didn't come back, because I did, 3-4 days later to see an inappropriate post accepted. I finalized the question and thought it was closed until I signed into my email and saw 10 emails from EE telling me that comments were added to this question, so I checked back to see the accepted answer changed. Giving me, the author, such few days to reply is really sneaky. It's like punishing me for having a life outside of EE.

It's really a shame that this whole thing happened. It really gives EE a bad image.

Regards,

Kody-Burg
Bravo, Kody-Burg!
We should not tolerate unjustified actions on the part of moderator.

modus_in_rebus, it is a pity you don't want to try to understand the essence of the story.
And the essence of it is that statement that while(true) is the cause of
infinite loop is by no means a solution.
while(true) is a perfectly legitimate device in java code, I used it in many
ggod programs and as long as there is a break inside the loop while(true) can very much serve the purpose. Inside this loop in the original
code there were even two break operations therefore simple statement
that while(true) is the cause of the infinite loop cannot be
the answer to the problem. And I'm sure, objects knows it better
than any of us.
Therefore, no matter what was happening with the deleting/not deleting of the question (of which  I was absolutely not aware because it  takes time and concentration to work on the code, and that' what I was doing at that time); one thing is obvious is that http:#35488076 cannot be considered to be the solution for this question.