I am extremely new to Java programming and have run into a roadblock for a school assignment. My program works in JGRASP and does not produce any errors. I get all the correct outputs. But when I submit the assignment I get the following error. I can't figure out what is wrong.
A run-time error occurred when running the SpaceTicket program: java.lang.StringIndexOutOfBoundsException: String index out of range: -23. Please test your program at home and fix the error before resubmitting. (2 occurrences)
The desired input is supposed to be:
12579500s15300701209817DSpaceX-001 Earth to Mars
Code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Random;
public class SpaceTicket
{
static final double STUDENT_DISCOUNT = 0.25;
static final double CHILD_DISCOUNT = 0.35;
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
String ticketCode = "";
String price = "";
String spaceTicket = "";
double priceParse = 0;
double cost = 0;
int ranNum = 0;
System.out.print("Enter ticket code: ");
ticketCode = userInput.nextLine();
ticketCode = ticketCode.trim();
if (ticketCode.length() < 25) {
System.out.println("*** Invalid ticket code ***");
System.out.println("Ticket code must have at least 25
characters.");
}
else {
price = ticketCode.substring(0, 6);
priceParse = Double.parseDouble(price);
if (ticketCode.charAt(8) == 's') {
cost = priceParse - (priceParse * STUDENT_DISCOUNT);
}
else if (ticketCode.charAt(8) == 'c') {
cost = priceParse - (priceParse * CHILD_DISCOUNT);
}
else {
cost = priceParse;
}
}
spaceTicket = ticketCode.substring(24, ticketCode.length());
System.out.println("Space Ticket: " + spaceTicket);
System.out.println("");
System.out.println("Date: " + ticketCode.substring(13, 15) + "/"
+ ticketCode.substring(15, 17) + "/" + ticketCode.substring(17,
21)
+ " Time: " + ticketCode.substring(9, 11) + ":"
+ ticketCode.substring(11, 13) + " Seat: "
+ ticketCode.substring(21, 24));
DecimalFormat df = new DecimalFormat("$#,##0.00");
priceParse = Double.parseDouble(price);
System.out.println("Price: " + df.format(priceParse)
+ " Category: " + ticketCode.charAt(8)
+ " Cost: " + df.format(cost));
Random generator = new Random();
ranNum = generator.nextInt(999999) + 1;
System.out.print("Prize Number: " + ranNum);
}
}