Question

I am trying to create a simple reservation system. I read lines from an input, before finish the project I write them to an output file.

My input is like

ADDTRAIN,Cumhuriyet,Regional,80,90,50,40

ADDTRAIN,Baskent,Express,80,90,1,2

ADDTRAIN,Baskent,Express,80,90,50,40

If one train has a same name with another I have to write "Command Failed... Train Name: ...."

I split them for comma then i create an Arraylist for Train.

File text = new File();
    PrintWriter writer = new PrintWriter();
    Scanner scnr = new Scanner(text);
  
    while(scnr.hasNextLine()){
       
        String line = scnr.nextLine();
        String[] atts = line.split(",");
        if(atts[0].equals("ADDTRAIN"))
        {
            train.add(new Train(atts[0],atts[1],atts[2],atts[3],atts[4],atts[5],atts[6]));
        }

    for(int i= 1; i<train.size(); i++)
    {
        writer.print(train.get(i-1).Writer());
        if(train.get(i).getTrainName().equals(train.get(i-1).getTrainName()))
        {
            writer.print(train.get(i).WrongWriter());
        }
    }
    
    scnr.close();
    writer.close();

I can only check for previous line. For example if my input is like

ADDTRAIN,Cumhuriyet,Regional,80,90,50,40

ADDTRAIN,Baskent,Express,80,90,1,2

ADDTRAIN,Baskent,Express,80,90,50,40

ADDTRAIN,Cumhuriyet,Regional,80,90,50,40

My program doesn't write a "Command Failed" line to output. How can i solve this problem?

Was it helpful?

Solution

You should use HashMap to store your data: Key=TrainName, Value=TrainObject. Using a HashMap provides both an easy and efficient way to check/disallow duplicates

if(trainMap.contains(trainName){ System.out.println("Error - train already exists"); }

OTHER TIPS

If you don't want to use a HashMap (which is a good solution), you can use two loops.

for(int i = 0; i<train.size(); i++)
{
    writer.print(train.get(i).Writer());
    for(int j = 0; j<train.size(); ++j)
    {
        if (i==j) continue;
        if(train.get(i).getTrainName().equals(train.get(j).getTrainName()))
        {
            writer.print(train.get(i).WrongWriter());
            break;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top