pimpvader pimpvader - 21 days ago 5
Java Question

search a array list using a split function

help I need to read a line from an array list file using a split.indexof( , ) function this is the code I already wrote to put the file into an array

import java.io.*; //For printwriter.
import java.util.*; //for scanner.
import javax.swing.*; //for JOption Pane.
public class dates


{public static void main(String[] args) throws IOException
{
//Ask user for birthday variables.
String userMonth;
userMonth = JOptionPane.showInputDialog("Please enter your birthday month ex: January");
String userDay;
userDay = JOptionPane.showInputDialog("Please enter your birthday day, ex: 5, or 24.");
Eventday(userMonth,userDay);
System.exit(0);
}
private static void Eventday(String userMonth, String userDay) throws IOException{


Scanner s = new Scanner(new File("\\Users\\user name\\Desktop\\eclipes\\famous date\\src\\famous dates.txt"));
ArrayList<String> list = new ArrayList<String>();
while(s.hasNext())
{
list.add(s.nextLine());
}s.close();
}
}


this is how the file look like

January, 1, (print the first line)
January, 2, (print the second line)
January, 3, (print the third line)


I would like to print the line base of the user inputs: birthday month and day?

Answer

To solve the problem you must first pass a valid path to the File constructor and then split the strings to get the event you want:

import java.io.*; //For printwriter.
import java.util.*; //for scanner.
import javax.swing.*; //for JOption Pane.
public class dates {
    public static void main(String[] args) throws IOException {
        //Ask user for birthday variables. 
        String userMonth; 
        userMonth = JOptionPane.showInputDialog("Please enter your birthday month ex: January"); 
        String userDay; 
        userDay = JOptionPane.showInputDialog("Please enter your birthday day, ex: 5, or 24."); 
        Eventday(userMonth,userDay);
        System.exit(0);
    }

    private static void Eventday(String userMonth, String userDay) throws  IOException{

        File file = new File("famous dates.txt");
        if(!file.exists())return;
        Scanner s = new Scanner(file);
        ArrayList<String> list = new ArrayList<String>();
        while(s.hasNext()) {
            list.add(s.nextLine());
        }
        s.close();

        for(String event : list) {
            String[] data = event.split(", ");
            if(data[0].equalsIgnoreCase(userMonth) && data[1].equalsIgnoreCase(userDay))
                System.out.println(data[2]);
        }
    }
}

I haven't tested the code yet but it should work as expected.