0
votes

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?

2
At what point in your code are you writing Command Failed?! - Bitmap
@Bitmap I'm guessing train.get(i).WrongWriter() returns the string? Dunno... - Duncan Jones
yeah. train.get(i).WrongWriter() write "Command Failed... Train Name:" error to the output. But it only checks previous line, not all objects. For train.get(0).getTrainName I don't need to check anything. But train.get(1) I need to check train.get(0).getTrainName. And for train.get(2) I need to check both train.get(0).getTrainName and train.get(1).getTrainName - Mert Serin

2 Answers

3
votes

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"); }

1
votes

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;
        }
    }
}