Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Java Program Infinate Loop

Posted on 2011-04-28
31
Medium Priority
?
515 Views
Last Modified: 2012-06-27
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

0
Comment
Question by:Kody-Burg
  • 12
  • 6
  • 5
23 Comments
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 35488076
>             while (true)

thats the cause of your infinite loop
0
 
LVL 92

Assisted Solution

by:objects
objects earned 2000 total points
ID: 35488082
as a first step change that method to:


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

0
 
LVL 6

Author Comment

by:Kody-Burg
ID: 35488091
There is still an infinate loop after fixing that.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Expert Comment

by:objects
ID: 35488127
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

0
 
LVL 92

Expert Comment

by:objects
ID: 35488133
I answered the question
0
 
LVL 6

Author Comment

by:Kody-Burg
ID: 35488142
No, the existing program still isn't fully functional, and I no longer need to fix it. I posted a two-part question.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35488163
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?
0
 
LVL 92

Expert Comment

by:objects
ID: 35488196
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
0
 
LVL 6

Author Comment

by:Kody-Burg
ID: 35488202
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.
0
 
LVL 92

Expert Comment

by:objects
ID: 35488208
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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35488224

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?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35488253

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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35488270
Why do you want to delete this question?
0
 
LVL 6

Author Comment

by:Kody-Burg
ID: 35488293
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.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35488304
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.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35516369
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?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35516625
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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35516651
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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35711303
>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.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35711523
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.

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35711762


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?


0
 
LVL 6

Author Comment

by:Kody-Burg
ID: 35712526
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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35713183
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.

 
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Loops Section Overview
Suggested Courses
Course of the Month21 days, 6 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question