Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Test for quit loop (a simple one!)  RSS feed

 
Kathy Talley
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to write code for a loop that will test for the word "quit." The code I have so far is posted, but I don't really even understand it because I'm just "fishing" for code anywhere I can find it. (I am an English major!) If someone can help me understand this, I would greatly appreciate it. I think I need a do...while loop. I think my code isn't working because I have declared a quit as a boolean data type and it is comparing it to a String that the user enters? Thanks!
 
Thana Bujakorn
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your problem is that you keep declaring String Object everytime you want to use it. By the way, you don't need the boolean quit for the program to work.
import javax.swing.JOptionPane;
public class Quit
{/** Main method*/
public static void main(String[] args) // JVM call this method.
{
String s = ""; // local variable should be explicitly initialized

do {s = JOptionPane.showInputDialog(null,"Enter a string: ,\n To quit program, enter quit","Input Box", JOptionPane.QUESTION_MESSAGE);
}while ( !s.equals ("quit"));
System.out.println(s);
System.exit(0);}}
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try creating more vaiables with good names, that will often help you see what is happening. Also, to avoid unpleasant surpises, give all your variables initial values right away when you create them.
Hopefully this will help you see how and why this code does what it does.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!