Search code examples
javainputoutputplaying-cards

Reading in card deck


I need some major help. I have no idea where to go. I'm completely out of my depth.

I need to read in a list of playing card codes from an input file in the format [RANK - SUITE].

Valid ranks are: 2-10, J, Q, K, A (Joker, Queen, King, Ace)

Valid suites are: C, D, H, S (Clubs, Diamonds, Hearts, Spades)

Then I need to output them to a file, so the input file would have 2-c and then the program would write to the output file:

Two of Clubs - Value = 2

I've pretty much gotten as far as selecting the input file (i'll post the code below), but I have no idea what to do. I'm thinking I need to use .nextline() to read each line but I don't know how to do that. Can someone help?

 public class CardTest {
 Scanner input = new Scanner(System.in);

 public static void main(String[] args) 
 {
  inputFile(); 
 }

 public static void inputFile ()
 {
   JFileChooser chooser = new JFileChooser();
   Scanner in = null; 
   Scanner console; 

   try {
   if (chooser.showOpenDialog(null) == JFileChooser.CANCEL_OPTION)
   {
       System.exit(0); 
   }
   if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
   {
       File selectedFile = chooser.getSelectedFile(); 
       in = new Scanner(selectedFile); 

   }
   }
   catch (FileNotFoundException e) 
   {
       JOptionPane.showMessageDialog(null, "Could not find the file, please type the file name into dialog box");
       System.out.println("Type in your input file"); 
       console = new Scanner(System.in);
       String selectedFile = console.next(); 
       in = new Scanner(selectedFile); 

   }
   in.close(); 
 }

Solution

  • You could go with the traditional String#replace way. Example below.

    File file = ...;
    try {
        Scanner scanner = new Scanner(file);
        while(scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] values = line.split("-");
            String rank = values[0].replace("[", "").trim();
            String suite = values[1].replace("]", "").trim();
            System.out.println(rank + " of " + suite + " - Value = " + rank); // *****
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    Input:

    [2-C]
    

    Output:

    2 of C - Value = 2
    

    You can and should modify that println function to your liking.