Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: Please help with arrays
|
Posted: May 3, 2003 12:13 PM
|
|
Hi, You've made an excellent start on your program. Sugestions:
add a while loop that iterates through your input box, so that you can continue to add Train objects.
Add an Exit option to allow the user to exit this loop.
If the Train.class file is in the same directory as Timetable.class you don't have to import it.
I did not understand why you had a import Time class or see any code for it, so I commented that out.
I would have chosen buttons in a Frame with a display window as a user interface. Yours will work as is.
The following is your code with some minor changes I had to make to get your two public classes to compile.
import javax.swing.JOptionPane;
//import Time;
//import Train;
public class Timetable
{
public static void main(String[]args)
{String choice, msg, inputa, inputd;
int a, d, inputar, inputdt, inc;
a=0;
d=0;
inc=0;
char ch;
//Train[] trains[];
//trains = new Train[10];
Train[] trains = new Train[10];
choice = JOptionPane.showInputDialog ("Input A-Add train, D-Delete Train, \n T-Timetable Display, F-Fastest Train");
ch = choice.charAt(0);
switch(ch)
{
case 'A':
case 'a':
inputd=JOptionPane.showInputDialog("Input departure time.");
inputa=JOptionPane.showInputDialog("Input Arrival time.");
inputdt=Integer.parseInt(inputd);
inputar=Integer.parseInt(inputa);
trains[inc] = new Train (inputdt,inputar);
inc++;
break;
case 'D':
case 'd':
String arr, dep;
int arrival, depature;
Train test, blank;
dep = JOptionPane.showInputDialog("Enter depature time");
arr = JOptionPane.showInputDialog("Enter arrival time");
arrival = Integer.parseInt(arr);
depature = Integer.parseInt(dep);
for(int i=0; i<10; i++)
{
test = new Train (depature,arrival);
blank = new Train (0,0);
//if (trains == test)
if (trains[i] == test)
{
//trains=blank;
trains[i]=blank;
System.out.println("deleted");
}
}
break;
case 'T':
case 't':
break;
case 'F':
case 'f':
int try1, try2;
try1 =0;
try2 = 0;
int fastest, index;
fastest =99999;
index = 0;
Train test1;
test1 = new Train(try1,try2);
for(int k=0;k<9;k++){
trains[k] = test1;
if((try2-try1)<fastest)
{
fastest = try2-try1;
index = k;}}
trains[index] = test1;
JOptionPane.showMessageDialog(null, "The fastest train departs at" + try1 + "arrives at" +try2 );
break;
default:
msg= "You did not enter A, D, T or F.";
JOptionPane.showMessageDialog (null, msg, "Error", JOptionPane.ERROR_MESSAGE);
}
System.exit(0);
}
}
No corrections are needed here. You are using an int value for your time. That should work for this application.
/* Generated by Together */
public class Train
{
int arrivaltime, departtime;
Train(int d, int a){
arrivaltime=a;
departtime=d;
}
}
Best wishes,
Charles
|
|