Results 1 to 2 of 2
  1. #1
    susan is offline Member
    Join Date
    Jul 2007
    Posts
    44
    Rep Power
    0

    Default Java Looping and decision

    I'm trying to do a simple program where a user inputs a String "course code" (predefined in an array) and then a loop searches to see what time the input course is at and displays the date/time for that particular course. I also want it to display an error if they input anything that doesn't match.

    The problem is that it just loops through the whole array every time and isn't really dependent on the 'if else' for some reason I can't figure out.

    Java Code:
    import javax.swing.*;
    public class ScheduleJ2
    {
      public static void main(String[] args)
      {
         String courseList[][]={{"COM101","Mon 08:00"},
                                {"COM201","Tue 09:00"},
                                {"COM301","Wed 11:00"},
                                {"COM315","Thu 14:00"},
                                {"COM401","Fri 16:00"},};
    
          String courseSelect = JOptionPane.showInputDialog(null, "Enter the Course Code to view the course date and time:\nCOM101\nCOM201\nCOM301\nCOM315\nCOM401");
    
          for(int i = 0; i<courseList.length;i++)
          {
             if(courseList[i][0].equalsIgnoreCase(courseSelect))
                 JOptionPane.showMessageDialog(null, "The course you selected is scheduled for: " + courseList[i][1]);		 
             else
     	 courseSelect = JOptionPane.showInputDialog(null, "Error - Course does not exist.\nPlease re-enter your course code:\nCOM101\nCOM201\nCOM301\nCOM315\nCOM401");
          }
    
      }
    }
    Thanks

  2. #2
    cachi is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default

    You can do this in one of two ways in Java. There are break statements and using boolean statements you can take advantage of.

    Break statements will break out of a loop right when it gets to the statement. So if we were to do
    Java Code:
    int i = 0;
    while(true)
    {
      if(i > 3)
        break;
      i++
    }
    This loop would break when I becomes greater then three.

    That is one way. The other way to separate execution would be to use a boolean variable to keep track of what is going on when. For example

    Java Code:
    boolean found = false;
    for(int i = 0; i < somelist.length() && !found; i++)
    {
      if(something.equals(somethingelse))
        found = true;
    }
    if(!found)
      System.out.println("Not Found");
    else
      System.out.println("Found");
    Greetings.

Similar Threads

  1. looping a function
    By Username in forum New To Java
    Replies: 2
    Last Post: 07-30-2007, 06:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •