Results 1 to 2 of 2
Thread: Java Looping and decision
- 07-13-2007, 09:48 PM #1
Member
- Join Date
- Jul 2007
- Posts
- 44
- Rep Power
- 0
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.
ThanksJava 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"); } } }
- 08-07-2007, 04:29 AM #2
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
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
This loop would break when I becomes greater then three.Java Code:int i = 0; while(true) { if(i > 3) break; i++ }
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
Greetings.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");
Similar Threads
-
looping a function
By Username in forum New To JavaReplies: 2Last Post: 07-30-2007, 05:37 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks