1

For example: Someone orders some movie passes: User enters : 3 tickets for Taken 2 at 17.50 How can I extract the quantity of tickets purchased, know the movie selected and total the costs from the entered string.

Any help is greatly appreciated.

                 String Mac1
         System.out.println("Enter num of tickets, movie & (at) ticket price:");
         Mac1 = input.nextLine();

         String Mov1[]= Mac1.split(", ");

           for (int i = 0; i < Mov1.length; i++) 
           {
               System.out.print(Mov1[i]);

           }

2 Answers2

2

Using regex appears a better fit here:

Matcher m = Pattern.compile("(\\d+) tickets for (.*) at (.*)").matcher(Mac1);
if (m.matches()) {
  int tickets = Integer.parseInt(m.group(1));
  String movie = m.group(2);
  double cost = Double.parseDouble(m.group(3));
  double total = tickets * cost;
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Seems like regular expressions are the best tool for the job (no matter how bad it looks):

(\\d+) tickets for (.*) at (\\d{1,2})[.:](\\d{2})
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • @ Chris, Number of tickets, for This_Movie at This price, I might need to add time into the string. –  Nov 10 '12 at 22:56