java.util.InputMismatchException error - java

Hey everyone I'am working on a project and am having a little trouble I am receiving a java.util.InputMismatchException any help would be greatly appreciated. I am really new to programming in java so forgive me if I've made a obvious dumb mistake. The object of the program is to read a file acquire the first three lines to use for 6 different variables(three integers and three strings) then read the rest of the file, format it,and do some math then put it into a new file. The file I am taking data from is formatted as follows.
Court 50
Box 10
Club 25
Rascal Conway 10 Box
Loretta Barrett 3 Court
Loras Tyrell 5 Club
Margaery Tyrell 8 Box.
Here is the code:
public class ProjectTicket {
public static void main(String[] args) throws IOException {
/////////////////////// amount of tickets person would buy
int amount;
/////////////////////// the tickets prices
int tprice1 = 0;
int tprice2 = 0;
int tprice3 = 0;
//////////////////////the ticket types
String ticket1 = null;
String ticket2 = null;
String ticket3 = null;
////////////////////// the total price
int price = 0;
////////////////////// customers name
String firstName;
String lastName;
////////////////////// name of seat type
String seat;
PrintWriter outputFile = new PrintWriter("portland2out.txt");
File file = new File("portlandvip2.txt");
Scanner inputFile = new Scanner(file);
////////////////////// getting ticket name and ticket price
for (int i = 0; i < 2; i++) {
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
ticket2 = inputFile.next();
tprice2 = inputFile.nextInt();
ticket3 = inputFile.next();
tprice3 = inputFile.nextInt();
outputFile.println(ticket1 + " " + "$" + tprice1);
outputFile.println(ticket2 + " " + "$" + tprice2);
outputFile.println(ticket3 + " " + "$" + tprice3);
}
////////////////////// getting customer name,number of tickets, type of ticket
while (inputFile.hasNext()) {
firstName = inputFile.next();
lastName = inputFile.next();
amount = inputFile.nextInt();
seat = inputFile.next();
////////////////////////////////// doing math for final billing.
if (seat.equals(ticket1))
price = tprice1 * amount;
else if (seat.equals(ticket2))
price = tprice2 * amount;
else if (seat.equals(ticket3))
price = tprice3 * amount;
///////////////////////////////// printing in format to file
outputFile.printf("%-10s%-10s$%,.2f\n", firstName, lastName, price);
}
inputFile.close();
}
}
Here is the error:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at BlancovichProject2.main(BlancovichProject2.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I'am not to sure what the problem can be. I've been looking around and it seems that type of error is given when the retrieved information is not exactly what it was looking for. Thanks again in advance for any help!

You are trying to use
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
on data which look like Rascal Conway 10 Box so you are trying to read Conway as integer which throws InputMismatchException.

It works but you just need to iterate only once or take off the forloop
change:
for (int i = 0; i < 2; i++) {
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
ticket2 = inputFile.next();
tprice2 = inputFile.nextInt();
ticket3 = inputFile.next();
tprice3 = inputFile.nextInt();
outputFile.println(ticket1 + " " + "$" + tprice1);
outputFile.println(ticket2 + " " + "$" + tprice2);
outputFile.println(ticket3 + " " + "$" + tprice3);
}
to this:
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
ticket2 = inputFile.next();
tprice2 = inputFile.nextInt();
ticket3 = inputFile.next();
tprice3 = inputFile.nextInt();
outputFile.println(ticket1 + " " + "$" + tprice1);
outputFile.println(ticket2 + " " + "$" + tprice2);
outputFile.println(ticket3 + " " + "$" + tprice3);
Also you have a wrong formating for the printf.To verify the results comment out the
//outputFile.printf("%-10s%-10s$%,.2f\n", firstName, lastName, price);
and add this to verify that you have the right output:
System.out.printf("%-10s%-10s$%,d\n", firstName, lastName, price);
then if they are right... you can output it to your file..

Related

How to store all the user inputs in do while loop, and call them to print later in Java program?

I have to write a Java program with do while loop. Basically it's like self-checkout register in grocery stores. At first program prompts user to enter Item 1 name and price, after we enter it asks "do you want to add more?" and prompts user. if we say yes then it repeats, add Item 2 (item number increments) name and price. So it goes like this till we say "no" or till entering 10 items. And after that program prints all item numbers correspondingly their names, and prices one by one. Also calculates total of all items. My code prints only last item number, name, price and total. I don't know how to merge array to do while.
Example how it should look:
_output: Enter Item1 and its price:_
_input: Tomatoes_
_input: 5.5_
_output: Add one more item?_
_input: yes_
_output: Enter Item2 and its price:_
_input: Cheese_
_input: 3.5_
_output: Add one more item?_
_input: yes_
_output: Enter Item3 and its price:_
_input: Apples_
_input: 6.3_
_output: Add one more item?_
_input: no_
_output: Item1: Tomatoes Price: 5.5, Item2: Cheese Price: 3.5, Item3: Apples Price: 6.3_
_output: Total price: 15.3_
Here's my code. It prints only last item's number, name and price with total. But can't manage to print all of them one by one as in example.
Scanner scan = new Scanner(System.in);
String item;
double price;
int i=1;
double total=0;
String quest;
String items [] = {};
do {
System.out.println("Enter item " + i + " and it's price:");
item = scan.next();
price=scan.nextDouble();
i++;
total=total+price;
System.out.println("Add one more item?");
quest=scan.next();
} while (quest.equalsIgnoreCase("yes")) ; {
System.out.println("Item "+i+": " + item + " Price: " + price + ",");
System.out.println("Total price: " + total);
}
You need to store each input in an array or collection, such as ArrayList.
If you choose to use an array, you can ask the user how many items will be entered then use that value for the length of the array:
System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();
String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];
If you decide you use a list, you do not need to ask the user for the list size, since lists are dynamically expanding data types:
List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();
Then for every iteration of your loop, you save the values into the arrays/lists:
System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();
String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];
for(int i = 0; i < ararySize; i++) {
System.out.println("Enter item " + (i + 1) + " and it's price:");
itemNames[i] = scan.next();
itemPrices[i] = scan.nextDouble();
// ...
}
// ...
Or for the list approach:
List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();
do {
System.out.println("Enter item " + i + " and it's price:");
itemNames.add(scan.next());
itemPrices.add(scan.nextDouble());
// ...
} while (quest.equalsIgnoreCase("yes")); {
// ...
}
Then you can iterate over the list/array to print your output:
for(int i = 0; i < itemNames.length; i++) {
String name = itemNames[i];
double price = itemPrices[i];
System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}
For list:
for(int i = 0; i < itemNames.size(); i++) {
String name = itemNames.get(i);
double price = itemPrices.get(i);
System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}
I finally solved the task. Thanks everybody who helped, really appreciated. Here's the code:
Scanner scan = new Scanner(System.in);
String itemName;
double price;
String[] items = new String[10];
double[] prices = new double[10];
int itemNumbers[] = new int[10];
String answer;
double total = 0;
int i = 1;
int index = 0;
do {
System.out.println("Enter item " + i + " and it's price:");
itemName = scan.next();
price = scan.nextDouble();
scan.nextLine();
total = total + price;
items[index] = itemName;
prices[index] = price;
itemNumbers[index] = i;
index++;
System.out.println("Add one more item?");
answer = scan.next();
i++;
} while (answer.equalsIgnoreCase("yes") && i <= 10); {
for (int j = 0; j < index; j++) {
System.out.print("Item " + itemNumbers[j] + ": " + items[j] + " price: " + prices[j] + ",");
}
}
System.out.println("\nTotal price: " + total);
This version works too. Without arrays.
String shoppingList = "";
String item = "";
String addMore = "";
double price = 0;
int count = 1;
double totalPrice = 0;
do {
System.out.println("Enter Item"+ count + " and its price:");
item = scan.next();
price = scan.nextDouble();
shoppingList += ("Item" + count + ": " + item + " Price: " + price + ", ");
totalPrice += price;
System.out.println("Add one more item?");
addMore = scan.next();
count++;
} while (addMore.equalsIgnoreCase("yes"));
System.out.println(shoppingList.substring(0, shoppingList.length()-2));
System.out.println("Total price: " + totalPrice);

Printwriter output not accepting .printf formatters to file?

When outputting to an already established file using the following code:
import java.util.Scanner;
import java.io.*;
public class BarakProductOrder
{
public static void main(String[] args) throws IOException
{
//Establish scanner object
Scanner input = new Scanner (System.in);
//Declare variables
String name, product, street, city, state, zip;
int qty;
double price;
//Collect data
System.out.println("Welcome to Matt's Dog Food Emporium!\n\nWhat is your name?");
name = input.nextLine();
System.out.println("Which product would you like to order today?");
product = input.nextLine();
System.out.println("How many would you like?");
qty = input.nextInt();
price = 4.56*qty;
input.nextLine(); //Must be placed to not skip over "address" line
System.out.println("Enter your street address:");
street = input.nextLine();
System.out.println("Enter the City:");
city = input.nextLine();
System.out.println("Enter the State (ex.: NY):");
state = input.nextLine();
System.out.println("Enter the Zip:");
zip = input.nextLine();
System.out.println("Thank you for your order, " + name);
//Output data to file "BarakOrder.txt"
PrintWriter outputFile = new PrintWriter("C:\\Users\\fbara\\Desktop\\CISS 110\\BarakOrder.txt");
outputFile.println("Order Number: 001");
outputFile.println("Product: " + product);
outputFile.println("Quantity: " + qty);
outputFile.printf("Price = 4.56*" + qty + " = $" + "%.2f" + price);
outputFile.println("Customer Contact Info: " + name);
outputFile.println("Address: " + street);
outputFile.println(city + ", " + state + " " + zip);
//Close scanner and file object
input.close();
outputFile.close();
System.out.println("Data has been written.");
}
}
Using the "%.2f" modifier at line 45 gives me the following error message:
java.util.MissingFormatArgumentException: Format specifier '%.2f' at
java.util.Formatter.format(Unknown Source) at
java.io.PrintWriter.format(Unknown Source) at
java.io.PrintWriter.printf(Unknown Source) at
BarakProductOrder.main(BarakProductOrder.java:45) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
Am I using the wrong modifier at the outputFile.printf? Or wrong ".print()" line?
That's not how printf works; you give it a format then the things to print.
You're not passing anything to format with the %.2f, you're trying to add it. The docs provide info on how to use it (and there are many examples in the world).
Roughly:
outputFile.printf("Price = 4.56*" + qty + " = $" + "%.2f", price);
Although I'm not sure why you wouldn't do the same formatting for qty.

code works but it keeps giving me the error: InputMismatchException and

I'm trying to work on a java program that takes prices from a text file, allows people to enter in the quantity of what they want, and print it out into another text file.
sample code
import java.io.*;
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.*;
// work on invoice
public class lab2_notes{
public static void main(String[] args)throws IOException {
Scanner fileIn = null;
try
{
// Attempt to open the file
// file should be in working directory
fileIn = new Scanner(new FileInputStream("prices.txt"));
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
System.out.println("File not found.");
// Shut the entire operation down
System.exit(0);
}
//convert file items to strings and numbers
String food_one;
double price_one;
String food_two;
double price_two;
String food_three;
double price_three;
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();
//give input varibles for user to enter in how much food they want
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = keyboard.nextLine( );
System.out.println("Enter your zip code: ");
int zip = keyboard.nextInt( );
System.out.println(food_one + " " + price_one);
int quanity_one = keyboard.nextInt( );
System.out.println(food_two + " " + price_two);
int quanity_two = keyboard.nextInt( );
System.out.println(food_two + " " + price_two);
int quanity_three = keyboard.nextInt( );
//use methods to work the code out
double pr_one = total_for_items(quanity_one, price_one);
double pr_two = total_for_items(quanity_two, price_two);
double pr_three = total_for_items(quanity_three, price_three);
double sub_total = (pr_one + pr_two + pr_three);
double taxation = tax(sub_total);
double final_total = grand_total(sub_total, taxation);
String invoice = Invoice(name, zip);
//convert to deciminal class
DecimalFormat df = new DecimalFormat("$#,###,##.##");
String con_sub = df.format(sub_total);
String con_tax = df.format(taxation);
String con_final = df.format(final_total);
String con_one = df.format(pr_one);
String con_two = df.format(pr_two);
String con_three = df.format(pr_three);
//print out recept on screen
System.out.println("Invoice Number: " + invoice);
System.out.println("Item Quantity Price Total");
System.out.println("======================================");
System.out.printf(food_one + " " + con_one + " " + price_one + " " + pr_one);
System.out.println(food_two + " " + con_two + " " + price_two + " " + pr_two);
System.out.println(food_three + " " + con_three + " " + price_three + " " + pr_three);
System.out.println("======================================");
System.out.println("Subtotal: " + con_sub);
System.out.println("6.25% sales tax: " + con_tax);
System.out.println("Total: " + con_final);
String a = "Invoice Number: " + invoice + "\n";
String b = "Item Quantity Price Total" + "\n";
String c = food_one + " " + con_one + " " + price_one + " " + pr_one + "\n";
String d = food_two + " " + con_two + " " + price_two + " " + pr_two + "\n";
String e = food_three + " " + con_three + " " + price_three + " " + pr_three + "\n";
String f = "======================================";
String g = "Subtotal: " + con_sub + "\n";
String h = "Total: " + con_final + "\n";
//print recept on a self-created text file
PrintWriter recept = new PrintWriter("recept.txt", "UTF-8");
recept.println(a + b + c + d + e + f + g + h);
recept.println();
recept.close();
fileIn.close();
}
public static double total_for_items(double qone, double price){
double total_one = qone * price;
return total_one;
}
public static double tax(double total){
double tax_amt = total * Math.pow(6.25, -2);
return tax_amt;
}
public static double grand_total(double total, double tax){
double g_total = total + tax;
return g_total;
}
public static String Invoice(String name, int zip_code){
String part_one = name;
int part_two = zip_code;
Scanner pileIn = null;
try
{
// Attempt to open the file
// file should be in working directory
pileIn = new Scanner(new FileInputStream(part_one));
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
System.out.println("File not found.");
// Shut the entire operation down
System.exit(0);
}
String Fname;
String Lname;
Fname = pileIn.nextLine();
pileIn.nextLine();
Lname = pileIn.nextLine();
//first part of name
String fnone = Fname.valueOf(Fname.charAt(1));
String fntwo = Fname.valueOf(Fname.charAt(2));
//second part of name
String lnone = Lname.valueOf(Lname.charAt(1));
String lntwo = Lname.valueOf(Lname.charAt(1));
//convert letters to uppercase
String con_fone_let = fnone.toUpperCase();
String con_ftwo_let = fntwo.toUpperCase();
String con_lnone_let = lnone.toUpperCase();
String con_lntwo_let = lntwo.toUpperCase();
String invoice_result = con_fone_let + con_ftwo_let + con_lnone_let + con_lntwo_let + zip_code;
return invoice_result;
}
}
However every time I start it, this error message pops up:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at lab2_notes.main(lab2_notes.java:46)
I'm new to coding with java and have been screwing with line 46 for hour now trying to figure it out.
what am I doing wrong?
Thanks, HG
Take input food_one to price three like this:
food_one = fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
price_two = fileIn.nextDouble();
fileIn.nextLine();
food_three = fileIn.nextLine();
price_three = fileIn.nextDouble();
It should work.
I changed the format in which you are storing the food and price (in prices.txt) to the following (with food and price separated by a delimiter, in this case a colon)
Pizz:20.10
Burger:10.30
Coffee:5.99
I changed the code to the following and now it is working. Hope this helps
// give strings and numbers varibles
String[] foodPrice = fileIn.nextLine().split(":");
food_one = foodPrice[0];
price_one = Double.parseDouble(foodPrice[1]);
foodPrice = fileIn.nextLine().split(":");
food_two = foodPrice[0];
price_two = Double.parseDouble(foodPrice[1]);
foodPrice = fileIn.nextLine().split(":");
food_three = foodPrice[0];
// fileIn.nextLine();
price_three = Double.parseDouble(foodPrice[1]);
Forgot to comment out fileIn.nextLine(); around like 46
your trying to put the name of a food into a nextDouble()
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();
Should be:
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
//fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();

Running a Java file from Eclipse on Mac

I'm writing a simple Java program for my history final project and am having trouble exporting it out of eclipse so it can be run on my teacher's computer (a Mac).
Here is the code:
package project;
import java.util.Scanner;
public class Denim {
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("What item of denim is in question?");
String str = scan.nextLine();
String str1 = str.toUpperCase();
String jeans = "JEANS";
String jeansp = "JEAN PANTS";
String tux = "CANADIAN TUXEDO";
String tux1 = "CANADIEN TUXEDO";
String tux2 = "CANADIAN TUX";
String tux3 = "CANADIEN TUX";
String jacket = "JACKET";
String jjacket = "JEAN JACKET";
String hat = "HAT";
String dhat = "DENIM BASEBALL HAT";
String bhat = "BASEBALL HAT";
String c = "C";
int jeanFactor = 9982;
double jacketFactor = 10466.25178;
double bottleFactor = 128/16.9;
double hatFactor = 314.1415;
if (str1.equals(jeans) || str1.equals(jeansp)){
System.out.println("How many pairs of jeans?");
int numj = scan.nextInt();
int gallonj = numj*jeanFactor;
System.out.println("Producing " + numj + " pairs of jeans would use: ");
System.out.println(gallonj + " gallons of water");
double bottlesj = gallonj*bottleFactor;
System.out.println(bottlesj + " bottles of water");}
else if ((str1.equals(tux)) || (str1.equals(tux1)) || (str1.equals(tux2)) ||(str.equals(tux3))){
System.out.println("How many tuxedos?");
int numt = scan.nextInt();
int gallontp = numt * jeanFactor;
double gallontj = numt * jacketFactor;
double gallont = gallontp + gallontj;
double bottlest = gallont*bottleFactor;
System.out.println("Producing " + numt +" " + c + str.substring(1,8) + " tuexedos would use: ");
System.out.println(gallont +" gallons of water.");
System.out.println(bottlest + " bottles of water");}
else if (str1.equals(jacket) || str.equals(jjacket)){
System.out.println("How many jackets?");
int numjj = scan.nextInt();
double gallonjj = numjj*jacketFactor;
double bottlesjj = numjj*bottleFactor;
System.out.println("Producing " + numjj + " jackets would use: ");
System.out.println(gallonjj + " gallons of water");
System.out.println(bottlesjj + " bottles of water");}
else if (str1.equals(hat) || str.equals(dhat) || str.equals(bhat)){
System.out.println("How many hats?");
int numh = scan.nextInt();
double gallonh = numh*hatFactor;
double bottlesh = numh*bottleFactor;
System.out.println("Producing " + numh + " jackets would use: ");
System.out.println(gallonh + " gallons of water");
System.out.println(bottlesh + " bottles of water");
}
}
}
I click file-export and export it as a .jar file, but every time I try and open it to run it, a message pops up saying "The Java JAR file could not be launched. Does anyone know how to fix this or what I'm doing wrong? Both my computer and my teacher's are Macbooks.

Converting output to include discounts when applicable

Here's the code I have so far
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Random;
public class TicketInfo
{
static final double STUDENT_DISCOUNT = .80;
static final double FACULTY_STAFF_DISCOUNT = .20;
/**
*Prints date, time, section, row, seat,
*price, cost, final cost with discount.
*
*#param args Command line arguements (not used).
*/
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("$#,##0.00");
DecimalFormat form = new DecimalFormat("###");
String ticketCode = "";
String event = "";
String date = "";
String time = "";
String section = "";
String row = "";
String seat = "";
String price = "";
String type = "";
String cost = "";
int section1, row1, seat1;
double price1, cost1;
Random generator = new Random();
int random;
System.out.print("Enter your ticket code: ");
ticketCode = userInput.nextLine();
System.out.println();
//Trims any extra white spaces.
ticketCode = ticketCode.trim();
if (ticketCode.length() > 27)
{
//Breaks down the ticket code into parts
type = ticketCode.substring(0, 3);
date = ticketCode.substring(14, 16) + "/"
+ ticketCode.substring(16, 18)
+ "/" + ticketCode.substring(18, 22);
time = ticketCode.substring(22, 24)
+ ":"
+ ticketCode.substring(24, 26);
section = ticketCode.substring(4, 5);
row = ticketCode.substring(5, 7);
seat = ticketCode.substring(8, 9);
price = ticketCode.substring(9, 12);
event = ticketCode.substring(26, ticketCode.length());
cost = ticketCode.substring(10, 14);
//Converts Doubles or Integers in a string into its numeric value.
section1 = Integer.parseInt(section);
row1 = Integer.parseInt(row);
seat1 = Integer.parseInt(seat);
price1 = Double.parseDouble(price);
cost1 = Double.parseDouble(cost);
//Calculate cost based on ticket type
random = generator.nextInt(999999) + 1;
// Print results
System.out.println("Event: " + event + " Date: "
+ date + " Time: " + time);
System.out.println("Section: " + form.format(section1) + " Row: "
+ form.format(row1) + " Seat: " + form.format(seat1));
System.out.println("Price: " + fmt.format(price1) + " Ticket Type: "
+ type + " Cost: " + fmt.format(price1));
System.out.println("Raffle Number: " + random);
}
else
{
System.out.println("Invalid Ticket Code.");
System.out.println("Ticket code must have at least 27 characters.");
}
}
}
Output as of now:
Enter your ticket code: STU01280712500091920151430Auburn vs LSU
Event: Auburn vs LSU Date: 09/19/2015 Time: 14:30
Section: 1 Row: 28 Seat: 7
Price: $125.00 Ticket Type: STU Cost: $125.00
Raffle Number: 939894
I need to make the cost output have discount included. For example, STU type = 80% discount, and F/S type = 20% and REG = no discount.
Goal is to make the cost include the 80% discount for STU ticket type which would make the cost 25.00 for student and 100.00 for faculty with a 20% discount. I think my problem is concerned with constants but I'm not sure since I'm a beginner.
You need to do an "if" condition with the type (LSU, STU, REG)
price1 = Double.parseDouble(price);
if(type.equals("STU")){
price1 = price1 * STUDENT_DISCOUNT;
}
else if(type.equals("LSU")){
price1 = price1 * FACULTY_STAFF_DISCOUNT;
}

Categories