Try catch problem in a while loop

I have computerGuess set to -1 and that starts the while loop.
but I need to catch exceptions that the user doesnt enter a string or anything other than a number between 1 and 1000.
but computerGuess is an int so that the while loop will start and I wanted to reset computerGuess from the user input using nextInt().
The problem is if I want to catch exceptions I have to take a string and parse it.
import java.util.Scanner;
public class Game {
     //initiate variables
     String computerStart = "yes";
     String correct = "correct";
     String playerStart = "no";
     int computerGuess = 500;
public void Start()
     //setup scanner
     Scanner input = new Scanner(System.in);
     int number = (int)(Math.random()*1001);
     System.out.println(welcome());
     String firstAnswer = input.nextLine();
     if(firstAnswer.equalsIgnoreCase(computerStart)== true)
          System.out.println(computerGuess());
          //while (userAnswer.equalsIgnoreCase(correct) == false){
               System.out.println();
     if(firstAnswer.equalsIgnoreCase(playerStart) == true)
          long startTime = System.currentTimeMillis();
          int currentGuess = -1;
          while (currentGuess != number){
          System.out.println(playerGuess());
          String guess = input.next();
          //currentGuess = Integer.parseInt(guess);
          if (currentGuess < number)
               System.out.println("too low");
          if (currentGuess > number)
               System.out.println("too high");
          if (currentGuess == number)
               long endTime = System.currentTimeMillis();
               System.out.println("Well done, the number is " + number);
          int i = -1;
          try {
            i = Integer.parseInt(guess);
               } catch (NumberFormatException nfe) {
                    //System.out.println("Incorrect input, please try again.");
          if ( i < 0 || i > 1000 ) {
               System.out.println("Incorrect input, please try again.");
     private String computerGuess()
           String comGuess = ("The computer will guess your number.\n" +
                    "Please enter \"too high\", \"too low\" or \"correct\" accordingly.");
           return comGuess;
     private String welcome()
          String gameWelcome = "Welcome to the guessing game \n" +
                                    "The objective is to guess a number between 1 and 1000.\n" +
                                    "You can guess the computer's number or it can guess your's.\n" +
                                    "You may enter \"quit\" at any time to exit.\n" +
                                    "Would you like the computer to do the guessing?";
          return gameWelcome;
     private String playerGuess()
          String playerWillGuess = "Guess a number between 1 and 1000.";
          return playerWillGuess;
}The catch works , but because computerGuess is int -1 so that the while loop will run, I cannot use the input to change computerGuess because it is a string.

the i was a mistake. and i commented on the other code, because it wasnt working at that moment. I need help understanding the try catch method.
I want to catch any input that isn't an integer , and I would also like to catch any input that isn't a string at other parts of my program.

Similar Messages

  • Try  Catch problem CS6

    All my try catch scripts don't work on CS6
    $.strict = false;
    function myGetScriptPath() {
    try{
    return app.activeScript;
    catch(myError){
    return File(myError.fileName);
    myGetScriptPath()
    Can anyone tell me the problem?
    Thanks
    Trevor

    Thanks for trying Pickory,
    I have Windows 7, with both indesign CS5 and creative cloud CS6 installed
    After experimenting I found that the script works fine on the machine with just CS5 on it.
    But on the one that has both doesn't work when called from either version of the ESTK but does from either version of indesign.
    When I try run the script from the CS5 ESTK It automatically opens and runs from the CS6 ESTK.
    I am not keen on uninstalling the CS5 ESTK as I don't know how long I'll keep creative cloud.
    Bellow is a alternative try catch script because the above one will not invoke an error if run from indesign so it won't call the catch.
    cs = app.activeDocument.characterStyles.item("myCharacterStyleName");
    try {alert ("Try $.strict = " +$.strict); myCharacterStyle.name}
    catch (myError) { alert ("Catch $.strict = " +$.strict + "\r" + myError)}
    I'm quite desperate for an answer.

  • Problem with Do-While Loop in a Binary Search

    The idea of the program is to randomly generate 10 integers, store them in an array then use a binary search to find the values at each position of the array in 10 or less steps.
    My problem is that the do-while loopisn't doing what it should be and I can't see the problem :S
    Thanks in advance.
    Se�n.
    int counter=0, guess=500, MIN=0, MAX=0;
    int arr[] = new int[10];
              for(int i=0; i<10; i++) {
          int ranNum= ( (int)(Math.random()*1000)+1 );
          arr=ranNum;
         System.out.println(ranNum);
         for(int j=0; j<10; j++) {
              do{
                   if(guess>arr[j]){
                        guess=MAX;
                        guess=guess/2;
                   else if(guess<arr[j]){
                        guess=MIN;
                        MAX=MIN*2;
    guess=((MAX-MIN)/2)+MIN;
                   else
                        guess=arr[j];
    }while(guess!=arr[j]);
              System.out.println("The number at position "+j+" in the array is :"+arr[j]);
    //resets the values each time the do-while loops breaks
              MIN=0;
              MAX=0;
              guess=500;

    Looks toe like MAX and MIN are always going to be zero.

  • Problems with a while loop within a method... (please help so I can sleep)

    Crud, I keep getting the wrong outputs for the reverseArray. I keep getting "9 7 5 7 9" instead of "9 7 5 3 1". Can you guys figure it out? T.I.A (been trying to figure this prog out for quite some time now)
    * AWT Sample application
    * @author Weili Guan
    * @version 1999999999.2541a 04/02/26
    public class ArrayMethods{
       private static int counter, counter2, ndx, checker, sum, a, size, zero;
       private static int length;
       private static int [] output2, output3, reverse, array;
       private static double output;
       private static double dblsum, dblchecker, average;
       public static void main(String[] args) {
          //int
          //int [] reverse;
          System.out.println("Testing with array with the values [1,3,5,7,9]");
          size = 5;
          array = new int [size];
          reverse = new int [size];
          array[0] = 1;
          array[1] = 3;
          array[2] = 5;
          array[3] = 7;
          array[4] = 9;
          System.out.println("Testing with sumArray...");
          output = sumArray(array);
          System.out.println("Sum of the array: " + sum);
          System.out.println();
          System.out.println("Testing with countArray...");
          output = countArray(array);
          System.out.println("Sum of the elements : " + checker);
          System.out.println();
          System.out.println("Testing with averageArray...");
          output = averageArray(array);
          System.out.println("The average of the array : " + average);
          System.out.println();
          System.out.println("Testing with reverseArray...");
          output2 = reverseArray(array);
          output3 = reverseArray(reverse);
          //System.out.print(reverse[4]);
          System.out.print("The reverse of the array : ");
          for(ndx = 0; ndx < array.length; ndx++){
             System.out.print(reverse[ndx] + " ");
       private ArrayMethods(){
       public static int sumArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if (array[ndx] > 0){
                checker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                sum += array[ndx];
                ndx++;
             return sum;
          else{
             sum = 0;
             return sum;
        /*Computes the sum of the elements of an int array. A null input, or a
        zero-length array are summed to zero.
        Parameters:
            array - an array of ints to be summed.
        Returns:
            The sum of the elements.*/
       public static int countArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if(array[ndx] > 0 && array[ndx] != 0){
                checker++;
             counter++;
          return checker;
        /*Computes the count of elements in an int array. The count of a
        null reference is taken to be zero.
        Parameters:
            array - an array of ints to be counted.
        Returns:
            The count of the elements.*/
       public static double averageArray(int[] array){
          dblchecker = 0;
          ndx = 0;
          counter = 0;
          dblsum = 0;
          while(counter < array.length){
             if(array[ndx] > 0){
                dblchecker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                dblsum += array[ndx];
                ndx++;
             average = dblsum / dblchecker;
             return (int) average;
          else{
             average = 0;
             return average;
        /*Computes the average of the elements of an int array. A null input,
        or a zero-length array are averaged to zero.
        Parameters:
            array - an array of ints to be averaged.
        Returns:
            The average of the elements.*/
       public static int[] reverseArray(int[] array){
          ndx = 0;
          counter = 0;
          counter2 = 0;
          if(array.length == 0){
             array[0] = 0;
             return array;
          else{
                //reverse = array;
             while(ndx <= size - 1){
                   reverse[ndx] = array[4 - counter];
                   counter++;
                   ndx++;
                   System.out.print("H ");
          return reverse;
        /*Returns a new array with the same elements as the input array, but
        in reversed order. In the event the input is a null reference, a
        null reference is returned. In the event the input is a zero-length array,
        the same reference is returned, rather than a new one.
        Parameters:
            array - an array of ints to be reversed.
        Returns:
            A reference to the new array.*/
    }

    What was the original question? I thought it was
    getting the desired output, " 9 7 5 3 1."
    He didn't ask for improving the while loop or the
    reverseArray method, did he?
    By removing "output3 = reverseArray(reverse):," you
    get the desired output.Okay, cranky-pants. Your solution provides the OP with the desired output. However, it only addresses the symptom rather than the underlying problem. If you'd bother yourself to look at the overall design, you might see that hard-coding magic numbers and returning static arrays as the result of reversing an array passed as an argument probably isn't such a great idea. That's why I attempted to help by providing a complete, working example of a method that "reverses" an int[].
    Removing everything and providing "System.out.println("9 7 5 3 1");" gets him the desired output as well, but (like your solution) does nothing to address the logic problems inherent in the method itself and the class as a whole.

  • Return statement and Try Catch problem

    Hi!!
    I've got the next code:
    public ResultSet DBSelectTeam(String query) {
    try {
    Statement s = con.createStatement();
    ResultSet rs = s.executeQuery(query);
    return rs;
    } catch (Exception err) {
    JOptionPane.showMessageDialog(null, "ERROR: " + err);
    But I need a return statement in the catch-block, but I don't know what's the best option.
    Help...
    Many thanks.

    The error message is: "missing return statement", Yes, I know.
    You have to either return from the catch statement, or throw from the catch statement, or return or throw after the catch statement.
    The only ways your method is allowed to complete is by returning a value or throwing an exception. As it stands, if an exception is thrown, you catch it, but then you don't throw anything and you don't return a value.
    So, like I said: What would you return from within or after catch? There's no good value to return. The only remotely reasonable choice would be null, but that sucks because now the caller has to explicitly check for it.
    So we conclude that catch shouldn't return anything. So catch must throw something. But what? You could wrap the SQLE in your own exception, but since the caller is dealing with JDBC constructs anyway (he has to handle the RS and close it and the Statement), there's no point in abstracting JDBC away. Plus he has to deal with SQLE anyway in his use of the RS and Statement. So you might as well just throw SQLE.
    So since you're going to just throw SQLE anyway, just get rid of the try/catch altogether and declare your method throws SQLException

  • Problem with a while loop.

    I'm very new to java so please bear with me!!!
    This is my code:
    import java.io.*;
    public class IfExample2
        public static void main (String[] args) throws IOException
         // Read in a number
         BufferedReader br = new BufferedReader(
                         new InputStreamReader (System.in));
         System.out.print ("Enter a number between 0 and 10 inclusive: ");
         String temp = br.readLine();
         double x = Double.parseDouble(temp);
         // check user input
         if (x > 10)
             System.out.println("The number you entered is too high");
              System.out.println("Please re-enter the number");
         else if (x < 0)
             System.out.println("The number you entered is too low");
              System.out.println("Please re-enter the number");
         else
             System.out.println("The number you entered is " + x);
    }Basically I want, if the number entered is too high or too low I want it to ask the user to re-enter the number, I want to use a while loop but I'm not sure where or how to use it, please help!

    while ( condition ) {
        // stuff here
    }More on while: [http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html]
    Edited by: oscarjustesen on Oct 7, 2008 5:40 PM
    Edited - fixed link

  • Plugin and try/catch problem

    I have a plug-in that was working perfectly until I added an FileOutputStream and its corresponding try/catch block. Now when I try to run my plugin, the popup menu come up corrctly but when I click to run my code it tells me the operation is not available. If I delete those three line it works fine again.
    Instead or try/catch I could do run() throws XYZException, but that gives an error. Any ideas how I can get this fixed? Thanks

    turns out that was not really what was causing the error. I was using the iText library, and I had added it to the classpath of the plugin but I didnt add it to the runtime classpath, so my 'new' eclipse windows was not working properly. Thanks anyways

  • A try catch problem....

    public class trycatch{
    public static void main(String[] adsf){
    int i;
    try{i = 5;}
    catch(Exception e){}
    System.out.println("hello"+i);
    }at compile time, the compiler says i might not have been initialised, but why?
    I have done it in try catch block.

    do you people have any better idea rather than put
    all the codes in one try catch block?Yes.
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.InputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    public class Test{
           public static void main(String[] param){
                  if(param.length!=4)
                  System.out.println("please provide 4 attributes: protocol, host, port, and file");
                  URL resource = null;
                  try{resource = new URL(param[0], param[1], Integer.parseInt(param[2]), param[3]);}
                  catch(MalformedURLException murle){System.out.println("an murle occurs");return;}
                  InputStream openResource = null;
                  try{openResource = resource.openStream();}
                  catch(IOException ioe){System.out.println("an ioe occurs");return;}
                  FileOutputStream toFile = null;
                  try{toFile = new FileOutputStream(param[3]);}
                  catch(FileNotFoundException fnfe){System.out.println("an fnfe occurs");return;}
                  try{
                  for(int i = openResource.read(); i!=-1; i = openResource.read())
                  toFile.write(i);
                  catch(IOException ioe){System.out.println("an ioe occurs");}
    }Notice the initialization. That will now at least compile. And before you get your knickers in a knot the return statements are there for terminiating execution of the method (in this case program) when an error occurs.

  • Dialog box problem in a while loop

    Hi!
    I would like to open a dialog box with one button. Therefore I am using the
    VI located in "time&dialog". I have a while-loop for the rest of my
    application. When I place this VI in this while loop, the dialog box opens
    always and not once. What do I have to do, to open it only once? Thank you
    for your help,
    Oliver.

    Hi Oliver,
    following Dennis answers and your reply, I attach a simple vi that shows a dialog when a value is out of range, but it is shown only once when the value is updated.
    Good luck,
    Alberto
    Attachments:
    out_of_range.vi ‏28 KB

  • Some code error-try catch problem

    import java.io.*;
    import java.sql.*;
    public class login1 extends HttpServlet
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException
    PrintWriter pw = res.getWriter();
    res.setContentType("text/html");
    String uid=(String)req.getParameter("formtext1");
    String pass=(String)req.getParameter("formtext2");
    Connection c;
    Statement s;
    ResultSet rs;
    ResultSetMetaData meta;
    try
    Class.forName("org.gjt.mm.mysql.Driver");
    c = DriverManager.getConnection("jdbc:mysql://localhost:3306/projectmanager?username=\"root\"&password=\"\"", "", "");
    s = c.createStatement();
    s.execute("select * from login order by userid ");
    rs = s.getResultSet();
    while(rs.next())
    if(uid.equals(rs.getString(1)) && pass.equals(rs.getString(2)))
         HttpSession ses=req.getSession(true);
    ses.putValue("a",uid);
    res.sendRedirect("welcome");
    catch(Exception e){
    {pw.println(e);}
         res.sendRedirect("login");}
    this page on getting exception is not directing to login again...could any1 help me out plzz.....

    What is it doing otherwise? Try putting a "return;" after the sendRedirect(). Also for future posts, put your code inside the "code" tags so its easier to read.

  • Try catch problem

    Here's my code:
    import javax.swing.*;
    import java.io.*;
    public class Customer
         try
              public RandomAccessFile file = new RandomAccessFile("customer.txt", "rw");
         catch(FileNotFoundException fnfe)
         public static void readCustomer(String telp)
         public static void writeCustomer(String telp, String name, String add1, String add2)
    and here's the error msg:
    C:\TEMP\Tar\TestOrder\Customer.java:7: illegal start of type
         try
    ^
    C:\TEMP\Tar\TestOrder\Customer.java:20: <identifier> expected
    ^
    2 errors
    Tool completed with exit code 1
    Can anyone pls tell what i did wrong? btw, i used TextPad to compile it
    Thanks
    Daffy

    hi,
    try and catch should be in a method.
    try this
    public class Customer
    public RandomAccessFile {
         try
    file = new RandomAccessFile("customer.txt", "rw");
         catch(FileNotFoundException fnfe)

  • Having problems with do.while loops

    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Assign32437 {
      public static void main(String[] args) {  // METHOD
       String strCost, strResVal, strUseLife, strDepre;
       double useLife = 0, deprec=0, Cost=0,resVal=0,accumulatedDepreciation = 0;
       double yearlyDepreciation = 0,Carryingvalue = 0;
       int repeat = 0, year = 0;
       DecimalFormat myFormat = new DecimalFormat("$0.00");
       JTextArea outputTextArea= new JTextArea();
         outputTextArea.append("\t\t Depreciation Schedule\n\n" + " End of year\t"
                               + "Cost\t" + "Yearly deprecation\t" +
                               "Accumulated Depreciation\t" + "Carrying value\n");
       do{   //ENTER COST OF ITEM
           strCost = JOptionPane.showInputDialog("Enter cost (>0):");
           Cost = Double.parseDouble(strCost);
        while (Cost < 0);
        do {       //ENTER ESTIMATED VALUE
           strResVal = JOptionPane.showInputDialog(
               "Enter residual value(>=0 and <cost:)");
           resVal = Double.parseDouble(strResVal);
        while (resVal < 0 || resVal > Cost);
        do {       //ENTER USEFUL LIFE
           strUseLife = JOptionPane.showInputDialog("Enter useful life(>0):");
           useLife = Double.parseDouble(strUseLife);
        while (useLife < 0);
        for (year = 0; year <= useLife; year++)
           deprec = (Cost - resVal) / (useLife);
           accumulatedDepreciation = (yearlyDepreciation * year); //CALCULATIONS
           Carryingvalue = (Cost - accumulatedDepreciation);
           outputTextArea.append(year + "\t" + Cost + "\t" + deprec + "\t" +
           accumulatedDepreciation + "\t" + Carryingvalue + "\n");
         JOptionPane.showMessageDialog(null, outputTextArea);
         repeat = JOptionPane.showConfirmDialog(null, "DO YOU WANT TO CONTINUE?\n",
                                                "Continue?",
                                                JOptionPane.YES_NO_OPTION);
         while(repeat==0);
       System.exit(0);
          }

    no error msgs. im not asking someone to do it for me. just looking for some pointers...
    when i run my code i am not being asked for more then one year ie: no loop is occuring. so i enter information and on my outputTextArea.append(year + "\t" + Cost + "\t" + deprec + "\t" +
           accumulatedDepreciation + "\t" + Carryingvalue + "\n"); displays one years totals like 30 times

  • Really having problems conditioni​ng while loop with a front pannel occurance

    Hi
    I was hoping somebody may be able to help me with a problem I am having running my vi so it acts on front panel occurrences.
    The vi in question "test platform v" is in the vi library I attach with this message.
    Basically I would like the vi to run continuously and each time I change the front panel values (which set the hardware) the updating loop stops the hardware is reset and the updating loop then continues.
    I guess I need to use occurrences so that the updating loop recognizes when the front panel values have changed so the new data can be written to the hardware.
    I am having trouble working out how to do this.  I guess so event based code would be best - I ama having trouble implementing this.
    I have simplified the code a lot to make the process of what I am trying to do easier to understand.
    Hope somebody can help.
    Many Thanks
    Attachments:
    big A 2 and tourist test platform.llb ‏1616 KB

    You need a few more tricks.  The answers you seek are in a very simple solution in the attached VI.
    You need to understand events and using property nodes with Signal (Very Important)
    Matt
    www.CompleteAutomatedSolutions.com
    Matthew Fitzsimons
    Certified LabVIEW Architect
    LabVIEW 6.1 ... 2013, LVOOP, GOOP, TestStand, DAQ, and Vison
    Attachments:
    genEvent.vi ‏31 KB

  • While loop problem

    I have a problem with a while loop in this code and it is really holding me up doing my degree. I can see nothing wrong with it but perhaps someone here can help. I would be really greatful if someone could. I have commented the line where the while loop starts about a third of the way down the code.
    Thanks
    Michael
    if (ae.getSource()==client_open)
    int row=0;
    check=true;
    row=client_listing.getSelectedRow();
    try
    System.out.println("information[row][1] is "+information[row][1]);
    if(information[row][1]!=null) //if the index is not null. Comment out this if statement to troubleshoot
    try
    InetAddress inet=InetAddress.getByName(information[row][1]);
    //Create a client socket on the listeners machone on port 7070
    client_socket=new Socket(inet,7070);
    System.out.println("Client port open on 7070 ");
    //Get the output as well as the input streams on that socket
    BufferedOutputStream out=new BufferedOutputStream(client_socket.getOutputStream());
    BufferedInputStream br_socket=new BufferedInputStream(client_socket.getInputStream());
    XMLWriter writer=new XMLWriter();
    writer.requestFString("SHOWFILES"," ");
    String file_data=writer.returnRequest();
    byte file_bytes[]=file_data.getBytes();
    int file_size=file_bytes.length;
    byte b[]=new byte[1024];
    // The methos takes a byte array and it's length as parameters and return
    // a byte array of length 1024 bytes....
    add_on upload=new add_on();
    System.out.println("Class of add_on created sucessfully");
    b=upload.appropriatelength(file_bytes,file_size);
    out.write(b,0,1024);
    /*An output stream is also initialised. This is used to store all the response
    from the listener */
    BufferedOutputStream out_file=new BufferedOutputStream(new FileOutputStream("response.xml"));
    int y=0;
    byte f[]=new byte[32];
    System.out.println("Entering while loop");
    //This while loop is not working. Any ideas. It just hangs here
    while((y=br_socket.read(f,0,32))>0) //the socket input stream is read
    out_file.write(f,0,y); //written on to the file output stream, y bytes from f start @ ofset 0
    out.close();
    br_socket.close();
    out_file.close();
    System.out.println("Exited while loop and closed streams");
    catch(Exception e)
    client_socket=null;
    check=false;
    System.out.println("Didnt enter try");
    try
    client_socket.close();
    catch(Exception e)
    System.out.println("Error occuered "+e.getMessage());
    row=0;
    if(check) //If the exception occurs then do not come here
    Vector parameters=new Vector();
    // A class SParser is also used here this class has a function/method of
    // the name perform which calls the xml parser to parse the xml file
    // generated by the response from the client soket...
    // the function perform returns a Vector which has the files/directories,
    // along with their flag information and size in case of files....
    SParser sp=new SParser();
    System.out.println("SParser object created sucessfully");
    parameters=sp.perform("response.xml");
    System.out.println("Parsing finished ");
    // The vector value returned by the xml parseris then passed as one of
    // the parameters to a class named file_gui this class is responsible for
    // displaying GUI consisting of a table and some buttons along with the
    // root information and flag..
    // Initially since the class is called for the first time the parameter
    // for the root is given the name "ROOT" and the Flag is set to "0"..
    file_gui showfiles=new file_gui(parameters,information[row][1],"Root","0");
    showfiles.show();
    check=false;
    } //end if
    } // end if
    } //end try
    catch(Exception e)
    row=0;
    } //end of ae.getSource()

    Why do you think it hangs at the while loop, eh? You need to put in additional printlns to justify your assertion. It takes alot less time to diagnose if you put in specific try/catch blocks with their own printlns - even if it is not as much fun. When you get into these kinds of troubles, there is no shame in putting in prints at each statement or logical point to track down the actual fault.
    ~Bill

  • Do while loop problem

    I have a problem with do while loop. I am displaying a dialogue box where a person should enter the type of quiz he had performed. The problem is that the user should enter only the following 3 words, either "Earthquakes" or "Place" or "Animals". If the user enters any other word, he/she should be displayed wwith another message saying "Invalid". This should keep repeatinf (i.e. displaying invalid) until the user enters either of those 3 words. When a user enters one of those words it will stop diplaying "Invalid". I tried doing this, but altough it displays "Invalid" when a user enters an invalid word, it will display invalid also when a user neters the correct word. I think i have something wrong with the loop.
    This is the code:
         String player = JOptionPane.showInputDialog(null, "Enter name");
                 String type = JOptionPane.showInputDialog(null, "Enter your quiz type");
                do
                    type = JOptionPane.showInputDialog(null, "Invalid entry. Try again." );
                 while (type != "Earthquakes"  || type != "Place" || type != "Animals" );

    Yeah thats a good idea, but i'm still a beginner and i'm still new to some things. I got a problem, because altough the while loop is working correctly, however the first time i enter a word even if its correct its still displays invalid. I think that thats a property of the while loop. So can someone pls tell me how can i change this loop and use another loop that wouldn't do this. Can i use perhaps a for loop instead here? Thanks a lot.
    String player = JOptionPane.showInputDialog(null, "Enter name");
              String type = JOptionPane.showInputDialog(null, "Enter your quiz type");
                  do {
                      type = JOptionPane.showInputDialog(null, "Invalid entry. Try again." );
                   } while(!type.equals("Earthquakes") && !type.equals("Places") && !type.equals("Animals"));
                Edited by: datax on Feb 21, 2008 10:46 AM

Maybe you are looking for

  • How do I include the heading of the table of contents in the table of contents?

    I am preparing a table of contents in InDesign CS3 (Macintosh OSX 10.5.8) I have added all the paragraph styles to the list of paragraph styles I want to appear in my Table of Contents. However, I would also like the table of contents itself to appea

  • How do I get my movies in geners on my Ipod?

    I have sorted my movies in genres in my itunes library, but how do I get them in genres (as with the music) on my Ipod instead of just as a long list? Is that possible to do?

  • Form does not contain Fragments when I run it

    Hi Folks, I've got a form which uses fragments.This form previews fine in the designer, but when I try to run it using generatePDF Output in a process, the parts that come from the fragments are gone. The following entries are in the log: 2011-03-04

  • MPD won't play AAC files from Streamripper

    I'm having some problems playing AAC files created by streamripper.  The files play just fine in Mplayer. This is the output I get in .mpd/log: faad: error decoding AAC stream: Invalid number of channels After googling I got the impression this might

  • How Do I format my Mac Pro Late 2013

    the mac pro late 2013 is well known the be equipped with a PCIe SSD .... Will the Erase function in disk utility with one time pass Zeros work or will it damage the drive? Thanks