Handling blank lines with txt input file and Scanner - java

I have my program complete. The one thing I need is a way for it to handle blank lines. I have read other posts but none have helped me implement them into my own code. I've tried various syntax within the loop that reads the file, but none have worked. Can someone help me please. This seems like it should be easier than it feels like currently. I'm trying to implement this into my code but am having trouble doing it. Below are my two classes and the input.txt. As is, this program runs as intended. Thanks for any help.
String line = in.nextLine();
while (line.length() == 0) {
if (in.hasNext()) {
line = in.nextLine();
} else {
break;
}
}
if (line.length() == 0) {
// reaches the end of input file
}
Product.java
/**
* Product
*
* A simple class framework used to demonstrate the design
* of Java classes.
*
* #author
* #version 02042015
*/
import java.util.*;
public class Product {
private String name;
private String code;
private int quantity;
private double price;
private String type;
private ArrayList<Integer> userRatings;
/*
* Product constructor
*/
public Product() {
name = "";
code = "";
quantity = 0;
price = 0.0;
type = "";
userRatings = new ArrayList<Integer>();
}
public Product(Product productObject) {
this.name = productObject.getName();
this.code = productObject.getInventoryCode();
this.quantity = productObject.getQuantity();
this.price = productObject.getPrice();
this.type = productObject.getType();
this.userRatings = new ArrayList<Integer>();
}
public Product(String name, String code, int quantity, double price, String type) {
this.name = name;
this.code = code;
this.quantity = quantity;
this.price = price;
this.type = type;
this.userRatings = new ArrayList<Integer>();
}
/*
* setName
* #param name - new name for the product
*/
public void setName(String name) {
this.name = name;
}
/*
* getName
* #return the name of the product
*/
public String getName() {
return name;
}
/*
* setType
* #param type - the type of the product
*/
public void setType(String type) {
this.type = type;
}
/*
* getType
* #return - the product type
*/
public String getType() {
return type;
}
/*
* setPrice
* #param price - the price of the product
*/
public void setPrice(double price) {
this.price = price;
}
/*
* getPrice
* #return the price of the product
*/
public double getPrice() {
return price;
}
/*
* setQuantity
* #param quantity - the number of this product in inventory
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/*
* getQuantity
* #return the number of this product in inventory
*/
public int getQuantity() {
return quantity;
}
/*
* setInventoryCode
* #param code - the new inventory code for the product
*/
public void setInventoryCode(String code) {
if(code.length()!= 8){
System.out.println("An invalid code has been entered. Please enter a code that is 8 characters in length.");
}
else{
}
this.code=code;
}
/*
* getInventoryCode
* #return the inventory code of the product
*/
public String getInventoryCode() {
return code;
}
/*
* setRatings
* #param code the new set of ratings for the product
*/
public void setRatings(ArrayList<Integer> Ratings){
this.userRatings = Ratings;
}
/*
* getRatings
* #return the ratings of the product
*/
public ArrayList<Integer> getRatings(){
return userRatings;
}
/*
* addUserRating
* NOTE: Each individual rating is stored with the product, so you need to maintain a list
* of user ratings. This method should append a new rating to the end of that list
* #param rating - the new rating to add to this product
*/
public void addUserRating(Integer rating1) {
if(rating1 > 5 || rating1 < 0){
System.out.println("You have entered an invalid rating. Please enter a rating between one and five stars.");
}
this.userRatings.add(rating1);
}
/*
* getUserRating
* NOTE: See note on addUserRating above. This method should be written to allow you
* to access an individual value from the list of user ratings
* #param index - the index of the rating we want to see
* #return the rating indexed by the value index
*/
public int getUserRating(int index) {
int a = this.userRatings.get(index);
return a;
}
/*
* getUserRatingCount
* NOTE: See note on addUserRating above. This method should be written to return
* the total number of ratings this product has associated with it
* #return the number of ratings associated with this product
*/
public int getUserRatingCount() {
int a = this.userRatings.size();
return a;
}
/*
* getAvgUserRating
* NOTE: see note on addUserRating above. This method should be written to compute
* the average user rating on demand from a stored list of ratings.
* #return the average rating for this product as a whole integer value (use integer math)
*/
public String getAvgUserRating() {
int sum = 0;
String avgRating = "";
if (userRatings.size() != 0){
for (int i = 0; i < this.userRatings.size(); i++) {
int a = getUserRating(i);
sum += a;
}
double avg = sum/this.userRatings.size();
if(avg >= 3.5){
avgRating = "****";
}
else if(avg >= 2.5){
avgRating = "***";
}
else if(avg >= 1.5){
avgRating = "**";
}
else if(avg >= 0.5){
avgRating = "*";
}
else{
}
}
else{
avgRating = "";
}
return avgRating;
}
}
Project02.java
/**
* Inventory Reporting Program
*
* A simple set of methods used to report and summarize
* the information read from an inventory file of product data
*
* #author
* #version 02042015
*/
import java.util.*;
import java.io.*;
public class Project02 {
public static void main(String[] args) {
//Establish the scanner so user input can be properly read.
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an inventory filename: ");
String fname = keyboard.nextLine();
ArrayList<Product> products = loadProducts(fname);
generateSummaryReport(products);
highestAvgRating(products);
lowestAvgRating(products);
largestTotalDollarAmount(products);
smallestTotalDollarAmount(products);
}
public static void generateSummaryReport (ArrayList<Product> Products){
int counter = 0;
System.out.println("Product Inventory Summary Report");
System.out.println("----------------------------------------------------------------------------------");
System.out.println();
System.out.printf("%-33s%-10s%-6s%-7s%-7s%-7s%-7s", "Product Name", "I Code", "Type", "Rating", "# Rat.", "Quant.", "Price");
System.out.println();
System.out.printf("%-33s%-10s%-6s%-7s%-7s%-7s%-7s", "-------------------------------", "---------", "----", "------", "------", "------", "------");
System.out.println();
while(counter < Products.size()){
System.out.printf("%-33s%-10s%-6s%-7s%6s%7s%7s", Products.get(counter).getName(), Products.get(counter).getInventoryCode(), Products.get(counter).getType(), Products.get(counter).getAvgUserRating(), Products.get(counter).getUserRatingCount(), Products.get(counter).getQuantity(), Products.get(counter).getPrice());
System.out.println();
counter++;
}
System.out.println("----------------------------------------------------------------------------------");
System.out.println("Total products in the database: " + Products.size());
}
/*
* loadProducts
* Given a filename, opens the file and reads Products from
* the file into an ArrayList of Product objects. Returns
* the ArrayList.
*
*
* #param fname - String containing the input file name
* #return - An ArrayList of Product objects
*/
public static ArrayList<Product> loadProducts(String fname) {
int a = 0;
Integer b = 0;
ArrayList<Product> products = new ArrayList<Product>();
try {
Scanner inFile = new Scanner(new File(fname));
while (inFile.hasNext()) {
int counter = 0;
String name = inFile.nextLine();
String code = inFile.nextLine();
int quantity = inFile.nextInt();
double price = inFile.nextDouble();
String type = inFile.next();
Product productObject = new Product(name, code, quantity, price, type);
while(inFile.hasNextInt() && counter==0){
a = inFile.nextInt();
if(a != -1){
b = new Integer(a);
productObject.addUserRating(b);
}
else{
counter = 1;
}
}
products.add(productObject);
if(inFile.hasNext()){
inFile.nextLine();
}
}
inFile.close();
}
catch (FileNotFoundException e) {
System.out.println("ERROR: " + e);
}
return products;
}
//Finds the item with the highest average user rating in stock
public static void highestAvgRating(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if(Products.get(counter).getAvgUserRating().length() > Products.get(a).getAvgUserRating().length()){
a = counter;
}
else{
}
counter++;
}
System.out.println("Highest Average User Rating In Stock: " + Products.get(a).getName() + " ("+Products.get(a).getAvgUserRating() + ")");
}
//Finds the item with the lowest average user rating in stock
public static void lowestAvgRating(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if(Products.get(counter).getAvgUserRating().length()<Products.get(a).getAvgUserRating().length()){
a=counter;
}
else{
}
counter++;
}
System.out.println("Lowest Average User Rating In Stock: "+Products.get(a).getName() + " ("+Products.get(a).getAvgUserRating() + ")");
}
//Finds the item with the largest total dollar amount in inventory (quantity * price)
public static void largestTotalDollarAmount(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if((Products.get(counter).getPrice())*(Products.get(counter).getQuantity()) > ((Products.get(a).getPrice())*(Products.get(a).getQuantity()))){
a=counter;
}
else{
}
counter++;
}
System.out.println("Item With The Largest Total Dollar Amount In Inventory: " + Products.get(a).getName() + " ($" + ((Products.get(a).getPrice())*(Products.get(a).getQuantity())) + ")");
}
//Finds the item with the smallest total dollar amount in inventory (quantity * price)
public static void smallestTotalDollarAmount(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if((Products.get(counter).getPrice())*(Products.get(counter).getQuantity()) < ((Products.get(a).getPrice())*(Products.get(a).getQuantity()))){
a=counter;
}
else{
}
counter++;
}
System.out.println("Item With The Smallest Total Dollar Amount In Inventory: " + Products.get(a).getName() + " ($" + ((Products.get(a).getPrice())*(Products.get(a).getQuantity())) + ")");
}
}
input.txt
The Shawshank Redemption
C0000001
100
19.95
DVD
4
5
3
1
-1
The Dark Knight
C0000003
50
19.95
DVD
5
2
3
-1
Casablanca
C0000007
137
9.95
DVD
5
4
5
3
-1
The Girl With The Dragon Tattoo
C0000015
150
14.95
Book
4
4
2
-1
Vertigo
C0000023
55
9.95
DVD
5
5
3
5
2
4
-1
A Game of Thrones
C0000019
100
8.95
Book
-1

When you decompose your question, you find there are two main concerns:
Read the input line-by-line
Skip the blank lines.
The first concern can be addressed with while (in.hasNext) in.nextLine(). To address the second concern, simply add a continue when you find the line is empty:
while (in.hasNextLine()) {
line = in.nextLine();
// skip blank lines
if (line.length() == 0) continue;
// do your magic
}
Now, how to get this in to your main program? It would be nice if we could somehow do: inFile.nextNonBlankLine(), right? So let's create our own scanner that has that method!
First things first, how would we like to use our own scanner? One example could be:
SkipBlankScanner in = new SkipBlankScanner(inFile);
while (in.hasNextNonBlankLine()) {
line = in.nextNonBlankLine();
}
Unfortunately Scanner is a final class, so we can't extend it to add our functionality. The next best thing is to use a delegate:
public class SkipBlankScanner {
private Scanner delegate;
private String line;
public SkipBlankScanner(Scanner delegate) {
this.delegate = delegate;
}
public boolean hasNextNonBlankLine() {
while (delegate.hasNextLine())
// return true as soon as we find a non-blank line:
if ((line = delegate.nextLine()).length > 0)
return true;
// We've reached the end and didn't find any non-blank line:
return false;
}
public String nextNonBlankLine() {
String result = line;
// in case we didn't call "hasNextNonBlankLine" before:
if (result == null && hasNextNonBlankLine())
result = line;
// try to read past the end:
if (result == null) throw new IllegalStateException();
line = null;
return result;
}
}
And there you have it, your very own Scanner that will ignore blank lines!
You could take this even further, and create a Scanner that will scan for entire Products, e.g. (with some Java-8):
public class ProductScanner {
private SkipBlankScanner scanner;
private Product product;
public ProductScanner(SkipBlankScanner scanner) {
this.scanner = scanner;
}
public boolean hasNextProduct() {
Product next = new Product();
if (fill(line -> next.setTitle(line)) &&
fill(line -> next.setInventoryCode(line)) &&
fill(line -> next.setQuantity(Integer.parseInt(line))) &&
fill(line -> next.setPrice(Double.parseDouble(line))) &&
fill(line -> next.setType(line))) {
try {
while (scanner.hasNextNonBlankLine() {
int rating = Integer.parseInt(scanner.nextNonBlankLine());
if (rating < 0) {
product = next;
return true;
}
next.addUserRating(rating);
}
} catch (NumberFormatException e) {
}
}
return false;
}
private boolean fill(Consumer<String> action) {
if (scanner.hasNextNonBlankLine() {
try {
action.accept(scanner.nextNonBlankLine());
return true;
} catch (Exception e) {
}
}
return false;
}
public Product nextProduct() {
Product result = product;
if (result == null && hasNextProduct())
result = product;
if (result == null)
throw new IllegalStateException();
product = null;
return result;
}
}

Related

Why the second product quantity override the first product quantity in java?

I was trying to develop an order system where it allows users to purchase stationery.
Here is how it works:
First, it will show the stationery menu and ask user to enter the id and quantity.
Then the item selected will be put inside a shopping cart, and if the user wants to buy the same product again, the system will add the quantity together and show the subtotal.
However, when user wanted to add another product that is not in the shopping list, it will show this
The quantity was added up with the previous product, which is not what i wanted.
I tried changing the code but it still gave me the same output
I would appreciate if anyone can point out my mistakes.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import static java.nio.file.Files.size;
import java.util.Scanner;
public class Order {
private int product_id;
private String product_Name;
private int orderQuantity = 0;
private double price = 0.0;
private double subTotal = 0;
int size = 100;
Product[] productList = new Product[size];
int count = 0;
Order[] orderList = new Order[size];
public Order() {
}
public Order(int product_id, String product_Name, double price, int orderQuantity) {
this.product_id = product_id;
this.product_Name = product_Name;
this.orderQuantity = orderQuantity;
}
public Order(int product_id, String product_Name, double price, double subTotal, int orderQuantity) {
this.product_id = product_id;
this.product_Name = product_Name;
this.price = price;
this.subTotal = subTotal;
this.orderQuantity = orderQuantity;
}
public String getProduct_Name() {
return product_Name;
}
public void setProduct_Name(String product_Name) {
this.product_Name = product_Name;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getOrderQuantity() {
return orderQuantity;
}
public void setOrderQuantity(int orderQuantity) {
this.orderQuantity = orderQuantity;
}
public Order(double subTotal) {
this.subTotal = subTotal;
}
public double getSubTotal() {
return subTotal;
}
public void setSubTotal(double subTotal) {
this.subTotal = subTotal;
}
public void Menu() {
System.out.println("Stationaries");
System.out.println("================");
System.out.println("ID Name Price Quantity");
System.out.println("=== =================== ===== ========");
try {
File product = new File("src/product.txt");
Scanner order = new Scanner(product);
while (order.hasNextLine()) {
String[] data = order.nextLine().split("\\|");
int product_id = Integer.parseInt(data[0]);
String product_name = data[1];
double product_price = Double.parseDouble(data[2]);
int product_quantity = Integer.parseInt(data[3]);
productList[count] = new Product(product_id, product_name, product_price, product_quantity);
count++;
System.out.printf("%-4d%-20s%-6.2f%-10d\n", product_id, product_name, product_price, product_quantity);
}
order.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public void makeOrder() {
char yesno;
boolean check = false;
int index = 0;
int count1 = 0;
int totalprice = 0;
int finalQuantity = 0;
boolean exist = false;
double product_price;
String product_Name;
Scanner order = new Scanner(System.in);
do {
System.out.print("Enter product ID :");
int product_Id = order.nextInt(); //1
product_Name = productList[product_Id - 1].getProduct_name();
product_price = productList[product_Id - 1].getProduct_price();
for (int i = 0; i < count; i++) {
if (product_Id == productList[i].getProduct_id()) {
check = true;
}
}
if (check) {
System.out.print("Enter quantity : ");
int quantity = order.nextInt();
orderList[count1] = new Order(product_Id, product_Name, product_price, quantity); //start from 0
count1++; //move to 1 //total 2 products
}
for (int k = 0; k < count1; k++) {
if (product_Id == orderList[k].getProduct_id()) { //if user enter prod 1, and prod 1 exist in the cart
index = k;
exist = true;
orderList[k].getProduct_id();
orderList[k].getOrderQuantity();
orderList[k].getPrice();
break;
}
}
System.out.println("Shopping Cart");
System.out.println("================");
System.out.println("ID Name Price Quantity Subtotal");
System.out.println("=== =================== ===== ======== ========");
if (exist) {
finalQuantity += orderList[index].getOrderQuantity();
orderList[index].setOrderQuantity(finalQuantity); //reset the quantity to the final version
orderList[index].setSubTotal(orderList[index].getOrderQuantity() * product_price);
System.out.printf("%-4d%-20s%-6.2f%-10d%-6.2f\n", orderList[index].getProduct_id(), orderList[index].getProduct_Name(), product_price, orderList[index].getOrderQuantity(), orderList[index].getSubTotal());
} else {
index++;
orderList[index].setProduct_id(orderList[index].getProduct_id()); //store at next array
orderList[index].setOrderQuantity(orderList[index].getOrderQuantity());
orderList[index].setSubTotal(orderList[index].getOrderQuantity() * product_price);
System.out.printf("%-4d%-20s%-6.2f%-10d%-6.2f\n", orderList[index].getProduct_id(), orderList[index].getProduct_Name(), product_price, orderList[index].getOrderQuantity(), orderList[index].getSubTotal());
}
// } else {
// index++;
// orderList[index].setProduct_id(orderList[index].getProduct_id()); //store at next array
// orderList[index].setOrderQuantity(orderList[index].getOrderQuantity());
// orderList[index].setSubTotal(orderList[index].getOrderQuantity() * product_price);
// System.out.printf("%-4d%-20s%-6.2f%-10d%-6.2f\n", orderList[index].getProduct_id(), orderList[index].getProduct_Name(), product_price, orderList[index].getOrderQuantity(), orderList[index].getSubTotal());
// }
//use later
// System.out.println("Final Shopping Cart");
// System.out.println("================");
// System.out.println("ID Name Price Quantity Subtotal");
// System.out.println("=== =================== ===== ======== ========");
//
// System.out.printf("%-4d%-20s%-6.2f%-10d%-6.2f\n", orderList[i + 1].getProduct_id(), orderList[i + 1].getProduct_Name(), product_price, orderList[i + 1].getOrderQuantity(), orderList[i + 1].getSubTotal());
// int num = 0;
// boolean exist = false;
// for (int j = 0; j < count1; j++) {
//
// if (orderList[j].getProduct_id() == num + 1) { //if id is 1
// exist = true;
// index = j;
//
// } else {
// num++;
// }
//
// }
//
// if (exist) {
// System.out.println("final quantity=" + (finalQuantity += orderList[index].getOrderQuantity()));
// }
System.out.print("Continue Order?(Y|N)");
yesno = order.next().toUpperCase().charAt(0);
} while (yesno == 'Y');
}
}
I think your design is not the best. The below code demonstrates my design. It consists of several classes. Refer to the comments in the below code which explain the design.
An Order contains Items where an Item is a Product together with a quantity.
(Notes after the code.)
package ordering;
import java.math.BigDecimal;
public record Product(int id, String name, BigDecimal price) {
public boolean equals(Object obj) {
boolean equal = this == obj;
if (!equal) {
if (obj != null) {
Class<?> thisClass = getClass();
Class<?> objClass = obj.getClass();
if (thisClass.equals(objClass)) {
Product other = (Product) obj;
equal = id == other.id();
}
}
}
return equal;
}
public int hashCode() {
return id;
}
}
package ordering;
import java.util.Objects;
/**
* An item in an order. An item consists of a product and the number of units of that product.
*
* #see ordering.Order
*/
public class Item {
/** Number of units ordered. */
private int amount;
/** Ordered product. */
private Product product;
/**
* Creates and returns an instance of this class.
*
* #param prod - product being ordered (cannot be null).
* #param amt - number of units of ordered product (must be positive).
*/
public Item(Product prod, int amt) {
Objects.requireNonNull(prod, "Null product.");
if (amt <= 0) {
throw new IllegalArgumentException("Amount must be positive.");
}
product = prod;
amount = amt;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public boolean equals(Object obj) {
boolean equal = this == obj;
if (!equal) {
if (obj instanceof Item) {
Item other = (Item) obj;
equal = product.equals(other.product);
}
}
return equal;
}
public int hashCode() {
return product.hashCode();
}
public String toString() {
return String.format("%3d\u00D7%s", amount, product);
}
/**
* Adjusts current amount by adding <var>amount</var> to it. Note that <var>amount</var> may be
* negative.
*
* #param amount - will be added to this instance's current amount.
*
* #throws UnsupportedOperationException if updated amount is not positive.
*/
public void updateAmount(int amount) {
int newAmount = this.amount + amount;
if (newAmount <= 0) {
throw new UnsupportedOperationException("Updated amount is not positive.");
}
this.amount += amount;
}
}
package ordering;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* An order consists of a list of items.
*
* #see ordering.Item
*/
public class Order {
private List<Item> items;
/**
* Creates and returns an instance of this class. Creates an order with zero items.
*/
public Order() {
items = new ArrayList<>();
}
public List<Item> getItems() {
return new ArrayList<>(items);
}
/**
* Removes <var>item</var> from the list of items in this order. Does nothing if this order
* does not contain <var>item</var>. A particular {#code Product} appears once only in a single
* order.
*
* #param item - item to remove.
*/
public void removeItem(Product item) {
findItem(item).ifPresent(i -> items.remove(i));
}
/**
* Updates the list of items in this order. If the order already contains <var>item</var> then
* <var>amount</var> is added to the current amount. Note that <var>amount</var> may be
* negative.
*
* #param item - item to update.
* #param amount - quantity of items.
*
* #throws UnsupportedOperationException if product amount, after update, is not positive.
*/
public void updateItem(Product item, int amount) {
findItem(item).ifPresentOrElse(itm -> itm.updateAmount(amount),
() -> items.add(new Item(item, amount)));
}
private Optional<Item> findItem(Product prod) {
if (prod != null) {
for (Item item : items) {
if (prod.equals(item.getProduct())) {
return Optional.of(item);
}
}
}
return Optional.empty();
}
}
This last class is the actual program.
package ordering;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Ordering {
private static final char YES = 'Y';
private static final Scanner STDIN = new Scanner(System.in);
private static final String DELIMITER = "|";
private static final String PRODUCTS = "product.txt";
private static List<Item> stock;
private static Order order;
private static boolean checkStock(Product prod, int amount) {
boolean enough = false;
for (Item item : stock) {
Product p = item.getProduct();
if (p.equals(prod)) {
int inStock = item.getAmount();
int newAmount = inStock - amount;
enough = newAmount >= 0;
if (enough) {
item.setAmount(newAmount);
}
else {
System.out.printf("Less than %d %s in stock.%n", amount, p.name());
}
}
}
return enough;
}
private static int getAmount() {
System.out.print("Enter quantity: ");
return STDIN.nextInt();
}
private static Product getProduct() {
System.out.print("Enter product ID: ");
int id = STDIN.nextInt();
Product prod = null;
for (Item item : stock) {
Product p = item.getProduct();
if (p.id() == id) {
prod = p;
break;
}
}
if (prod == null) {
System.out.println("Unknown product.");
}
return prod;
}
private static void initializeStock() throws IOException {
Path path = Paths.get(PRODUCTS);
try (Stream<String> lines = Files.lines(path)) {
stock = lines.map(Ordering::makeItem)
.filter(i -> i != null)
.collect(Collectors.toList());
}
}
private static Item makeItem(String line) {
Item item;
String[] parts = line.split("\\" + DELIMITER);
if (parts.length == 4) {
int id = Integer.parseInt(parts[0]);
BigDecimal price = new BigDecimal(parts[2]);
Product prod = new Product(id, parts[1], price);
item = new Item(prod, Integer.parseInt(parts[3]));
}
else {
item = null;
}
return item;
}
private static void makeOrder() {
order = new Order();
boolean more = true;
do {
showMenu();
Product prod = getProduct();
if (prod != null) {
int amount = getAmount();
if (checkStock(prod, amount)) {
try {
order.updateItem(prod, amount);
}
catch (UnsupportedOperationException x) {
// Ignore.
}
}
showOrder();
}
STDIN.nextLine();
System.out.print("Continue Order?(Y|N) ");
String answer = STDIN.nextLine();
more = answer.length() > 0 && answer.toUpperCase().charAt(0) == YES;
} while (more);
}
private static void showMenu() {
System.out.println("Stationaries");
System.out.println("============");
System.out.println("ID Name Price Quantity");
System.out.println("=== =================== ===== ========");
for (Item item : stock) {
Product p = item.getProduct();
System.out.printf("%3d %-19s %5.2f %d%n",
p.id(),
p.name(),
p.price().doubleValue(),
item.getAmount());
}
}
private static void showOrder() {
if (order != null) {
List<Item> items = order.getItems();
if (items.size() > 0) {
System.out.println("Your order:");
System.out.println("ID Name Price Quantity Cost");
System.out.println("=== =================== ===== ======== ======");
BigDecimal total = new BigDecimal(0);
for (Item item : order.getItems()) {
Product prod = item.getProduct();
int amount = item.getAmount();
BigDecimal cost = prod.price().multiply(new BigDecimal(amount));
total = total.add(cost);
System.out.printf("%3d %-19s %5.2f %8d %.2f%n",
prod.id(),
prod.name(),
prod.price().doubleValue(),
amount,
cost);
}
System.out.printf("Total: %.2f%n", total);
}
else {
System.out.println("Nothing ordered.");
}
}
}
public static void main(String[] args) {
try {
initializeStock();
makeOrder();
showOrder();
System.out.println("\nGood bye.");
}
catch (IOException x) {
x.printStackTrace();
}
}
}
It is recommended to use [class] BigDecimal, rather than [primitive] double for handling money.
I believe you need at least JDK 9 to run the above code.
Output from a sample run of the above code:
Stationaries
============
ID Name Price Quantity
=== =================== ===== ========
1 rulers 1.00 400
2 pen 4.00 700
Enter product ID: 1
Enter quantity: 1
Your order:
ID Name Price Quantity Cost
=== =================== ===== ======== ======
1 rulers 1.00 1 1.00
Total: 1.00
Continue Order?(Y|N) y
Stationaries
============
ID Name Price Quantity
=== =================== ===== ========
1 rulers 1.00 399
2 pen 4.00 700
Enter product ID: 1
Enter quantity: 1
Your order:
ID Name Price Quantity Cost
=== =================== ===== ======== ======
1 rulers 1.00 2 2.00
Total: 2.00
Continue Order?(Y|N) y
Stationaries
============
ID Name Price Quantity
=== =================== ===== ========
1 rulers 1.00 398
2 pen 4.00 700
Enter product ID: 2
Enter quantity: 1
Your order:
ID Name Price Quantity Cost
=== =================== ===== ======== ======
1 rulers 1.00 2 2.00
2 pen 4.00 1 4.00
Total: 6.00
Continue Order?(Y|N) n
Your order:
ID Name Price Quantity Cost
=== =================== ===== ======== ======
1 rulers 1.00 2 2.00
2 pen 4.00 1 4.00
Total: 6.00
Good bye.
The code
finalQuantity += orderList[index].getOrderQuantity();
will always increase the value in the variable finalQuantity, which you save later with the code
orderList[index].setOrderQuantity(finalQuantity);
However, you don't set (or reset) the variable finalQuantity to the current quantity of your order/product. That's why you will get the current result of 3 instead of the expected result of 1, because in the previous loop/iteration, that variable was set to 2.
When you want to update the quantity, you need to read the current quantity first and set it in the variable finalQuantity before increasing it by the user input.
On a side note: Your code is structured in an unclear way, which looks (and maybe is) wrong. Your Order class contains different code logic, one for managing one order entry, but also for managing the menu/userinteraction. That makes it weird to have Order[] orderList = new Order[size]; inside the Order class (specially as a field member). It is also not clear if the Order class is in fact for one single order of possible multiple products (in different quantities) or if it has multiple orders (of what?).
You might also want to look into java.util.List<T> and java.util.Map<K,V> to have a container with dynamic size and to save the quantities for each product selected.

how do i collect everything after a certain substring value

in here i want to collect everything after a substring and set it as their specfic field.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
*
* class StudentReader for retrieveing data from file
*
*/
public class StudentReader {
public static Student[] readFromTextFile(String fileName) {
ArrayList<Student> result = new ArrayList<Student>();
File f = new File(filename);
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
String text = n.nextLine();
}
n.close();
String hold1[] = text.Split(",");
String hold2[] = new String[hold1.length];;
for(int i = 0; i < hold1.length(); ++i) {
hold2[i] = hold1.Split("=");
if (hold2[i].substring(0,3).equals("name")) {
}
}
return result.toArray(new Student[0]);
}
}
backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this
Student{name=Jill Gall,age=21,gpa=2.98}
I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name
im using this link as a reference but I don't see what actually does it
How to implement discretionary use of Scanner
I think the bug is in following lines,
while (n.hasNextLine()) {
String text = n.nextLine();
}
Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.
Actual it should be,
List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
inputs.add(n.nextLine());
}
You can use above inputs list to manipulate your logic
By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):
public class Student {
// Member Variables...
String studentName;
int studentAge = 0;
double studentGPA = 0.0d;
// Constructor 1:
public Student() { }
// Constructor 2: (used to fill instance member variables
// right away when a new instance of Student is created)
public Student(String name, int age, double gpa) {
this.studentName = name;
this.studentAge = age;
this.studentGPA = gpa;
}
// Getters & Setters...
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public double getStudentGPA() {
return studentGPA;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
#Override
public String toString() {
return new StringBuilder("").append(studentName).append(", ")
.append(String.valueOf(studentAge)).append(", ")
.append(String.valueOf(studentGPA)).toString();
}
}
I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* class StudentReader for retrieving data from file
*
*/
public class StudentReader {
private static final Scanner userInput = new Scanner(System.in);
private static Student[] studentsArray;
public static void main(String args[]) {
String underline = "=====================================================";
String dataFilePath = "StudentsFile.txt";
System.out.println("Reading in Student data from file named: " + dataFilePath);
if (args.length >= 1) {
dataFilePath = args[0].trim();
if (!new File(dataFilePath).exists()) {
System.err.println("Data File Not Found! (" + dataFilePath + ")");
return;
}
}
studentsArray = readFromTextFile(dataFilePath);
System.out.println("Displaying student data in Console Window:");
displayStudents();
System.out.println(underline);
System.out.println("Get all Student's GPA score average:");
double allGPA = getAllStudentsGPAAverage();
System.out.println("GPA score average for all Students is: --> " +
String.format("%.2f",allGPA));
System.out.println(underline);
System.out.println("Get a Student's GPA score:");
String sName = null;
while (sName == null) {
System.out.print("Enter a student's name: --> ");
sName = userInput.nextLine();
/* Validate that it is a name. Should validate in
almost any language including Hindi. From Stack-
Overflow post: https://stackoverflow.com/a/57037472/4725875 */
if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
+ "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
break;
}
else {
System.err.println("Invalid Name! Try again...");
System.out.println();
sName = null;
}
}
boolean haveName = isStudent(sName);
System.out.println("Do we have an instance of "+ sName +
" from data file? --> " +
(haveName ? "Yes" : "No"));
// Get Student's GPA
if (haveName) {
double sGPA = getStudentGPA(sName);
System.out.println(sName + "'s GPA score is: --> " + sGPA);
}
System.out.println(underline);
}
public static Student[] readFromTextFile(String fileName) {
List<Student> result = new ArrayList<>();
File f = new File(fileName);
try (Scanner input = new Scanner(f)) {
while (input.hasNextLine()) {
String fileLine = input.nextLine().trim();
if (fileLine.isEmpty()) {
continue;
}
String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
String studentName = "";
int studentAge = 0;
double studentGPA = 0.0d;
// Get Student Name (if it exists).
if (lineParts.length >= 1) {
studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];
// Get Student Age (if it exists).
if (lineParts.length >= 2) {
String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("\\d+")) {
studentAge = Integer.valueOf(tmpStrg);
}
// Get Student GPA (if it exists).
if (lineParts.length >= 3) {
tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
studentGPA = Double.valueOf(tmpStrg);
}
}
}
}
/* Create a new Student instance and pass the student's data
into the Student Constructor then add the Student instance
to the 'result' List. */
result.add(new Student(studentName, studentAge, studentGPA));
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
return result.toArray(new Student[result.size()]);
}
public static void displayStudents() {
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return;
}
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i].toString());
}
}
public static boolean isStudent(String studentsName) {
boolean found = false;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return found;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return found;
}
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
break;
}
}
return found;
}
public static double getStudentGPA(String studentsName) {
double score = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return score;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return score;
}
boolean found = false;
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
score = studentsArray[i].getStudentGPA();
break;
}
}
if (!found) {
System.err.println("The Student named '" + studentsName + "' could not be found!");
}
return score;
}
public static double getAllStudentsGPAAverage() {
double total = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return total;
}
for (int i = 0; i < studentsArray.length; i++) {
total += studentsArray[i].getStudentGPA();
}
return total / (double) studentsArray.length;
}
}

addScore method is over writing current array values instead of appending to the current list

I am a novice java student. I have a project for a java class where I am to write a Golfer class, Score class and a tester for the Golfer class to test all methods. The specific problems I am having is :
When I call the addScore method, the method overwrites the old data instead of adding to the existing. I need to get the program to add the scores in the array in addition to the previous score.
The findScore method is private and used in the public method getScore, however, when I run the program, I get the null value regardless of the parameter in the call. I need to return the index of an array based on the date entered.
The following is excerpts from the code and not the entire program.
public class Golfer {
/**String representing the golfer's name*/
private String name;
/**String representing the golf course where the golfer's hadicap is kept*/
private String homeCourse;
/**Unique integer that identifies every golfer*/
private int idNum;
/**Array storing all the golfer's scores*/
private Score[] scores;
public static int nextIDNum;
/**Default constructor, sets all instance field to a default value. Creates Array.
*/
public Golfer() {
name = "";
homeCourse = "";
scores = new Score[0];
nextIDNum = 1000;
}
/**Constructor sets name and homeCourse from parameters and uses the static variable nextIDNum to retrieve the next available ID number. Creates Array.
*/
public Golfer(String golferName, String home) {
setName(golferName);
setHomeCourse(home);
setNextIDNum(nextIDNum);
scores = new Score[10];
}
/**Creates a Score object from the parameters that represent the course, course rating, course slope, date and score.  Adds the newly created Score object to the Array of Scores. 
#param golfCourse A String representing the golf course name
#param rating A double representing the golf course rating
#param slope An int representing the golf course slope
#param scoreDate A String representing the date the course was played
#param score An int representing what was scored on the course
*/
public void addScore(String golfCourse, double rating, int slope, String scoreDate, int score) {
Score[] golfScores = new Score[scores.length + 1];
for (int i = 0; i < scores.length; i++) {
golfScores[i] = scores[i];
}
golfScores[golfScores.length - 1] = new Score(golfCourse, rating, slope, scoreDate, score);
scores = golfScores;
}
/**Deletes a score from the Array based on score date,  Assumes only one score per day.
#param golfDate A string representing the date of the golf score
#return true if score found and deleted,
#return false if score not found.
*/
public boolean deleteScore (String golfDate) {
for (int i = 0; i < scores.length; i++) {
if (findScore(golfDate) > 0) {
scores[i] = null;
}
return true;
}
return false;
}
/**Returns a score object based on the score date. If not found returns null
#param golfDate The date of the golf score
#return Scores[i] The score on the parameterized date
#return null A null value if the score was not found.
*/
public Score getScore(String golfDate) {
for (int i = 0; i < scores.length; i++) {
if (findScore(golfDate) > 0) {
return scores[i];
}
}
return null;
}
/**Given a parameter representing the score's date, finds the score on a given date and returns the Array index of a score. Return constant NOTFOUND if not found.
#param golfDate A string representing the date of the score
#return i An array index representing the score
#return NOTFOUND A constant set to -1 if the score isn't found
*/
private int findScore(String golfDate) {
final int NOTFOUND = -1;
for (int i = 0; i < scores.length; i++) {
if (scores[i].equals(golfDate)) {
return i;
}
}
return NOTFOUND;
}
}
The score class:
public class Score {
private String courseName;
private int score;
private String date;
private double courseRating;
private int courseSlope;
public Score(String course, double rating, int slope, String golfDate, int scr) {
setCourseName(course);
setScore(scr);
setDate(golfDate);
setCourseRating(rating);
setCourseSlope(slope);
}
public Score() {
courseName = "";
score = 0;
date = "";
courseRating = 0.0;
courseSlope = 0;
}
public void setCourseName(String course) {
courseName = course;
}
public String getCourseName() {
return courseName;
}
public void setScore(int golfScore) {
if ((golfScore < 40) && (golfScore > 200)) {
golfScore = 9999;
System.out.println("Error: golf score must be between 40 and 200.");
}
score = golfScore;
}
public int getScore() {
return score;
}
public void setDate(String golfDate) {
date = golfDate;
}
public String getDate() {
return date;
}
public void setCourseRating(double rating) {
if ((rating < 60) && (rating > 80)) {
rating = 9999;
System.out.println("Error: the course rating must be between 60 and 80.");
}
courseRating = rating;
}
public double getCourseRating() {
return courseRating;
}
public void setCourseSlope(int slope) {
if ((slope < 55) && (slope > 155)) {
slope = 9999;
System.out.println("Error: The course slope must be between 55 and 155.");
}
courseSlope = slope;
}
}
The tester class:
public class GolferTester {
public static void main (String []args) {
String course1 = "Augusta National";
String course2 = "Bayhill CC";
String course3 = "TPC Sawgrass";
String player1 = "Sam Snead";
String player2 = "Arnold Palmer";
String player3 = "Jack Nicklaus";
int score1 = 66;
int score2 = 201;
int score3 = 72;
int slope1 = 60;
int slope2 = 156;
int slope3 = 77;
double rating1 = 65.2;
double rating2 = 81.8;
double rating3 = 70.9;
String date1 = "01/01/2017";
String date2 = "06/01/2016";
String date3 = "12/22/2016";
Golfer golfer1 = new Golfer(player1, course1);
Golfer golfer2 = new Golfer(player2, course2);
Score s1 = new Score(course1, rating1, slope1, date1, score1);
Score s2 = new Score(course2, rating2, slope2, date2, score2);
s1.setScore(score1);
s1.setDate(date1);
s1.setCourseRating(rating1);
s1.setCourseSlope(slope1);
s1.setCourseName(course1);
s2.setScore(score3);
s2.setDate(date3);
s2.setCourseRating(rating3);
s2.setCourseSlope(slope3);
s2.setCourseName(course3);
golfer1.addScore(s1.getCourseName(), s1.getCourseRating(), s1.getCourseSlope(), s1.getDate(), s1.getScore());
golfer2.addScore(s2.getCourseName(), s2.getCourseRating(), s2.getCourseSlope(), s2.getDate(), s2.getScore());
System.out.println(golfer1);
System.out.println("");
System.out.println(golfer2);
System.out.println("");
s1.setScore(score2);
s1.setCourseRating(rating2);
s1.setCourseSlope(slope2);
golfer1.addScore(s1.getCourseName(), s1.getCourseRating(), s1.getCourseSlope(), s1.getDate(), s1.getScore());
System.out.println(golfer1);
deleteScore(s1.getDate());
System.out.println(s1.getDate());
}
}
Any help would be appreacited
Don't use an array for a list of elements that you know will grow/shrink. Use ArrayList, which has add()
Your getScore method is returning null always

Java, JDBC: Updating & displaying values in/from SQLite db

Question:
How do I update numberOfWins in the db as the program runs(rounds of poker are played), & at the end of program execution, display the data in/from my db?
Background:
This is a fairly standard console based poker game. Table is a dealer(creates hands) & executes rounds. PokerGameMain, the main. I also have classes for Card, Deck, Player, Wallet. 3 players are dealt cards, creating a hand, the hands are played, there is a winner & looser, this is a round. I have included my current code on these classes for context.
My questions are about two database/JDBC/SQLite classes(SQLiteJDBC, Database) I am attempting to implement. I've added these solely for learning purposes. I'm attempting to gain knowledge of database/JDBC/SQLite & maven(which I have used to manage my SQLite dependency).
I've working pretty diligently at this program but I'm having a little trouble seeing how to pull it together.
Question Again:
Primary) How do I:
Create a db(poker)...done I think.
Create a table(players), with 2 columns(palyerName, numberOfWins)...done I think.
Create 3 rows(player1-3)...done I think.
Update numberOfWins in the db as the program runs(rounds of poker are played), & at the end of program execution, display the data in my db
Secondary) Suggestions regarding:
My exception handling & design in SQLiteJDBC & Database
SQLiteJDBC
Note:
The only errors in the program that I know of are an unchecked exception & a can not resolve method. Both in SQLiteJDBC, here & here:
try {
db.execute(dropTable);
db.execute(createTable);
db.execute(insertInto1);
db.execute(insertInto2);
db.execute(insertInto3);
ResultSet resultSets = db.executeQuery(selectFrom);
try {
while (resultSets.next()) {
// read the result set
System.out.println("player = " + resultSets.getString("playerName"));
System.out.println("number of wins = " + resultSets.getInt("numberOfWins"));
}
}
try {
db.close();
}
package com.craigreedwilliams.utilities;
import java.sql.*;
/**
* Created by Reed on 7/10/2015.
*/
public class SQLiteJDBC {
public static void passQuery() {
String dropTable = "DROP TABLE if EXISTS players";
String createTable = "CREATE TABLE players(VARCHAR(25) playerName, INTEGER numberOfWins)";
String insertInto1 = "INSERT INTO player1 VALUES ('player1', 0)";
String insertInto2 = "INSERT INTO player2 VALUES ('player2', 0)";
String insertInto3 = "INSERT INTO player3 VALUES ('player3', 0)";
String selectFrom = "SELECT * FROM players";
// Url for SqlLite
String jdbcDbType = "jdbc:sqlite";
String dbName = "poker.db";
String dbUrl = jdbcDbType + ":" + dbName;
Database db = new Database(dbUrl);
try {
db.execute(dropTable);
db.execute(createTable);
db.execute(insertInto1);
db.execute(insertInto2);
db.execute(insertInto3);
ResultSet resultSets = db.executeQuery(selectFrom);
try {
while (resultSets.next()) {
// read the result set
System.out.println("player = " + resultSets.getString("playerName"));
System.out.println("number of wins = " + resultSets.getInt("numberOfWins"));
}
}
finally {
try {
resultSets.close();
}
catch (Exception ignore) {
}
}
}
finally {
try {
db.close();
}
catch (Exception ignore) {
}
}
}
}
Database
package com.craigreedwilliams.utilities;
import java.sql.*;
/**
* Created by Reed on 7/10/2015.
*/
public class Database {
public String dbUrl;
private String sqliteDriver = "org.sqlite.JDBC";
private String driver;
private Connection connection = null;
private Statement statement = null;
public Database() {
}
public Database(String dbUrl) {
this.dbUrl = dbUrl;
// sqliteDriver = getDriverString(dbUrl);
try {
setConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setConnection() throws Exception {
try {
// registered DriverName using the current class loader
Class.forName(sqliteDriver);
}
catch (Exception e) {
// connection failed
System.out.println("DriverName: " + driver + " was not available");
System.err.println(e);
throw e;
}
// create a database connection
connection = DriverManager.getConnection(dbUrl);
try {
statement = connection.createStatement();
}
catch (Exception e) {
try {
connection.close();
}
catch (Exception ignore) {
}
connection = null;
}
}
// this method should undoubtedly be public as we'll want to call this
// to close connections externally to the class
public void closeConnection() {
if (statement!=null) {
try {
statement.close();
}
catch (Exception ignore) {
}
}
if (connection!=null) {
try {
connection.close();
}
catch (Exception ignore) {
}
}
}
// and we will definitely want to be able to call the following two
// functions externally since they expose the database
// behaviour which we are trying to access
public ResultSet executeQuery(String query) throws SQLException {
return statement.executeQuery(query);
}
public void execute(String query) throws SQLException {
statement.executeUpdate(query);
}
}
PokerGameMain
package com.craigreedwilliams.game;
import java.util.Scanner;
/**
* Hello world!
*
*/
public class PokerGameMain
{
public static void main(String[] args) {
//Input Object of the scanner class
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to Poker Table! May the odds forever be in your favor :)");
do {
printMainGameWelcomeMenu();
choice = input.nextInt();
switch (choice){
case 1:
//call start game method or class here
startGame();
break;
case 2:
//end game here
printMainGameGoodbyeMessage();
break;
default:
System.out.println("The value you entered is outside of the range required for this application...");
}
} while (choice != 2);
}
public static void printMainGameWelcomeMenu(){
System.out.println("This is the poker game's menu: \n"
+ "To start the game enter: 1\n"
+ "To end game enter: 2\n");
}
public static void printMainGameGoodbyeMessage(){
System.out.println("Thank you for playing the poker game! Hope you enjoyed your experience. Have a great day! :D");
}
public static void startGame(){
int count = 1;
Table table = new Table();
getUserInput(table);
while (count < 4) {
System.out.println("Round : " + count + "...\n");
table.dealCards();
table.showCards();
count++;
}
}
public static void getUserInput(Table table){
Scanner usrInput = new Scanner(System.in);
boolean anteSet = false;
System.out.println("Before the game starts, I will need some information...\n");
System.out.println("What is your name?");
String name = usrInput.nextLine();
//set player name
table.getPlayerAt(0).setPlayerName(name);
// set ante
do {
System.out.println("How much are you willing to bet for every round? Keep in mind there will have to be at least three rounds...");
Double ante = usrInput.nextDouble();
if(checkAnte(ante, table.getPlayerAt(0).getWallet())) {
table.getPlayerAt(0).setAnteValue(ante);
anteSet = true;
}
}while (!(anteSet));
}
public static boolean checkAnte(double ante, Wallet wallet){
if (ante * 3.0 > wallet.getBalance()) {
System.out.println("Sorry your wallet balance is less than you think...Please reconsider the ante value");
return false;
}
else
{
wallet.deductFromBalance(ante);
System.out.println("Your ante for each round is set to be: " + ante + ". Good luck!");
return true;
}
}
}
Table
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Table {
// two private attributes
private Player[] players;
private Deck deck;
private double pot;
private Player winner;
/******************************************
** The array is set in the following way:
******************************************
** pairs are each given 1 point **
** three of a kind are given 3 points **
** straights are given 5 points **
** flush are given 7 points **
** four of a kind are given 8 points **
** royal straights are given 10 points **
** royal flush are given 12 points **
******************************************
*/
private int[][] game = new int [7][2];
// constructor initializes the deck and cards
public Table() {
deck = new Deck();
players = new Player[3];
players[0] = new Player();
players[1] = new Player();
players[2] = new Player();
deck.shuffle();
}
// getter for player at the given index
public Player getPlayerAt(int index){
return players[index];
}
// deals the card to each player
public void dealCards() {
int count = 0;
for (int i = 0; i < players[0].getCards().length; i++) {
for (int j = 0; j < players.length; j++) {
players[j].setCardAtIndex(deck.getCard(count++), i);
}
}
}
// simulates the game and shows the result
public void showCards() {
for (int i = 0; i < players.length; i++) {
System.out.print("Player " + (i + 1) + ": \n");
for (int j = 0; j < players[0].getCards().length; j++) {
System.out.println("{" + players[i].getCardAtIndex(j).toString() + "} ");
}
if(players[i].countPair() > 0) {
System.out.println("Pair(S):" + players[i].countPair() + "! \n");
game[0][i] += players[i].countPair();
}
if(players[i].isFlush()) {
System.out.println("Flush! ");
}
if(players[i].isRoyalFlush())
System.out.println("Royal Flush!!\n");
if(players[i].isThreeOfAkind())
System.out.println("Three of a kind! ");
if(players[i].isFourOfAkind())
System.out.println("Four of a kind!!\n");
if(players[i].isStraight())
System.out.println("Straight! \n");
if(players[i].isRoyalStraight())
System.out.println("Royal Straight!!\n");
else
System.out.print("\n");
}
}
}
Wallet
package com.craigreedwilliams.game;
import java.util.Random;
/**
* Created by Reed on 7/11/2015.
*/
public class Wallet {
private double balance;
/**
* default Wallet constructor
*/
public Wallet() {
setRandomStartingBalance(50.0, 500.0);
}
private void setRandomStartingBalance(double minimum, double maximum) {
Random random = new Random();
double randomStartingBalance = minimum + (maximum - minimum) * random.nextDouble();
balance = randomStartingBalance;
}
public double getBalance() {
return balance;
}
public void deductFromBalance(double price) {
this.balance = balance - price;
}
}
Player
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Player {
private final static int MAX = 5;
private Card cards[]; //hand
private Deck tempDeck = new Deck();
private Double anteValue = 0.0;
private Wallet wallet;
private String playerName = "";
int gamesWon = 0;
// private bools for checks
private boolean pair = false;
private boolean threeOfAkind = false;
private boolean fourOfAkind = false;
private boolean royalStraight = false;
private boolean royalFlush = false;
//constructor initializes 5 cards in each hand
public Player() {
cards = new Card[MAX];
wallet = new Wallet();
}
// getters are setters for name and ante value
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public Double getAnteValue() {
return anteValue;
}
public void setAnteValue(Double anteValue) {
this.anteValue = anteValue;
}
// getter for wallet for player object
public Wallet getWallet() {
return wallet;
}
// getter and setter for games won so far...
public int getGamesWon() {
return gamesWon;
}
public void setGamesWon(int gamesWon) {
this.gamesWon = gamesWon;
}
//returns all the cards in hand
public Card[] getCards() {
return cards;
}
//get the cards at a particular position
public Card getCardAtIndex(int index) {
return (index >= 0 && index < MAX) ? cards[index] : null;
}
//sets the card at particular position
public void setCardAtIndex(Card c, int index) {
if(index >= 0 && index < MAX)
cards[index] = c;
}
// basic bool return functions
public boolean isRoyalStraight() {
return royalStraight;
}
public boolean isThreeOfAkind() {
return threeOfAkind;
}
public boolean isFourOfAkind() {
return fourOfAkind;
}
public boolean isRoyalFlush() {
return royalFlush;
}
//Main Logic here : public functions that check for all winning hands and change private boolean variables
// appropriately
//counts number of matched pair
public int countPair() {
int count = 0;
//boolean pairCheck = ((!(threeOfAkind) && (!(fourOfAkind))));
for (int i = 0; i < cards.length; i++) {
for (int j = i + 1; j < cards.length; j++)
{
if (cards[i].getRank().equals(cards[j].getRank())){
count++;
if (count == 1)
pair = true;
else if ((pair) && (count == 3)) {
threeOfAkind = true;
pair = false;
}
else if ((threeOfAkind) && (count == 4)) {
fourOfAkind = true;
threeOfAkind = false;
}
}
}
}
return (pair) ? count : 0;
}
//checks if it is a flush or not i.e all five cards of same suit also checks for royal flush
public boolean isFlush()
{
int count = 0;
for (int i = 0; i < cards.length; i++) {
for (int j = i + 1; j < cards.length; j++) {
if (cards[i].getSuit().equals(cards[j].getSuit())) {
count++;
}
}
if (count == 5){
if (cards[i].getRankInt() == tempDeck.getRankInt(12))
royalFlush = true;
}
}
return ((count == 5) && (!(royalFlush))) ? true : false;
}
//checks to see if it is a straight or royal straight or neither
public boolean isStraight(){
int count = 0;
for (int i = 0; i < cards.length - 1; i++){
if ((cards[i].getRankInt() + 1 == cards[i + 1].getRankInt()) && (count < 4)){
count++;
}
else if (count == 4){
if (cards[i].getRankInt() == tempDeck.getRankInt(13)){
royalStraight = true;
}
}
}
return ((count == 4) && (!(royalStraight))) ? true : false;
}
}
Deck
package com.craigreedwilliams.game;
import java.util.Calendar;
import java.util.Random;
/**
* Created by Reed on 7/10/2015.
*/
public class Deck {
private final String rank[] = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King", "Ace"};
private final String suits[]={"Hearts","Diamonds","Clubs","Spades"};
private final int rankInt[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
private final int suitsInt[] = {1, 2, 3, 4};
private Card deck[];
private final int MAX = 52;
private Random randNum;
//makes the deck, constructor - no arguments
public Deck() {
deck = new Card[MAX];
//uses calendar object to get time stamp
Calendar cal = Calendar.getInstance();
long seed = cal.getTimeInMillis();
randNum = new Random(seed); // random generated using time seed
// uses modulus operator
for(int i = 0; i < deck.length; i++ ){
deck[i] = new Card( rank[i % 13], suits[i / 13], rankInt[i % 13], suitsInt[i / 13]);
}
}
//shuffles the deck
public void shuffle(){
for(int i = 0; i < deck.length; i++ ){
int j = randNum.nextInt(MAX);
Card c = deck[i];
deck[i] = deck[j];
deck[j] = c;
}
}
//returns the individual card in the deck
public Card getCard(int index){
return deck[index];
}
//returns rankInt from the deck object at the given index value
public int getRankInt(int index) {
return rankInt[index];
}
}
Card
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Card {
private String rank;
private String suit;
private int rankInt;
// TODO: remove this if actually never used
private int suitInt;
//four argument constructor initializes Cards rank and suit (stings and ints)
public Card(String rank, String suit, int rankInt, int suitInt) {
super();
this.rank = rank;
this.suit = suit;
this.rankInt = rankInt;
this.suitInt = suitInt;
}
//getter method to return the rank value
public String getRank() {
return rank;
}
//getter method to return the suit value
public String getSuit() {
return suit;
}
//setter method to initialize the suit
public int getRankInt() {
return rankInt;
}
//return String representation of Card object
public String toString() {
return rank + " : " + suit;
}
}
Your SQL query should look like this:
Select Player,Wins From yourtable Set Wins=Wins + 1 Where Player=playerid
The columns are just examples because I don't know how you called them ;)
And at the end of each round you just need to query your SQL-Server.

something wrong with the calculateWeeklypay methods of each employees

well i have now four types of employees. Managers (who receive a fixed weekly salary), Design workers (who receive a fixed hourly wage for up to the first 40 hours they work and "time-and-a-half," i.e., 1.5 times their hourly wage, for overtime hours worked), Sales workers (who receive a $250 plus 5.7% of their gross weekly sales), and Manufacturing (who receive a fixed amount of money per item for each of the items they produce -- each manufacture in this company works on only one type of item). and here are my classes:
employee class
the problem is i get this output:
You chose to open this file: Employees.txt
John Smith Manufacturing 6.75 120 444
0.0
Betty White Manager 1200.0 0 111
0.0
Stan Slimy Sales 10000.0 0 332
250.0
Betty Boop Design 12.5 50 244
0.0
meaning that it is getting 0 for all my calculations and leading to this weekly report:
WEEKLY PAY REPORT FOR Wacky Widgets COMPANY
Employee
0
WEEKLY PAY
250
Total Payroll: $0.0
Total number of managers paid:1
Total number of Design Employees paid:1
Total number of Sales Employees paid:1
Total number of Manufacturing Employees paid:1
i need help with fixing my methods so they can accept the integers of the file and use them in the calculation since all i'm getting at the moment are 0 values. i can provide my read-file method if it is need . thanks
here is the abstract class from which all the other employees type are extending from
[code]
public abstract class Employee {
public abstract double calculateWeeklyPay();
private String fName;
private String lName;
private int EmpId;
private Position p;
/*
public Employee()
{
}*/
/**
* default constructor
*/
public Employee() {
// TODO Auto-generated constructor stub
/*this.getFName();
this.getLName();
this.getEmpId();*/
getFName();
getLName();
this.getEmpId();
}
/**
* #param string first name
* #param string2 last name
* #param y position
*/
public Employee(String string, String string2, String y) {
fName = string;
lName = string2;
// EmpId=string3;
if (y.equals("Design")) {
p = Position.Design;
}
if (y.equals("Sales")) {
p = Position.Sales;
}
if (y.equals("Manufacturing")) {
p = Position.Manufacturing;
}
if (y.equals("Manager")) {
p = Position.Manager;
}
// StringTokenizer str=new StringTokenizer(fName+ lName+y,": .");
}
/**
* #return first name
*/
public String getFName() {
return fName;
}
/**
* #param firstName sets the first name
*/
public void setFName(String firstName) {
this.fName = firstName;
}
/**
* #return last name
*/
public String getLName() {
return lName;
}
/**
* #param lastName
*/
public void setLName(String lastName) {
this.lName = lastName;
}
/*public String toString()
{
// String str = firstName+" "+lastName+" "+"Position: "+getPosition();
return firstName;
}*/
/**
* #return p position
*/
public Position getPosition() {
// String str = firstName+" "+lastName+" "+"Position: "+getPosition();
return p;
}
public String toString() {
String str = fName + " " + lName + " " + "Position: " + getPosition();
return str;
}//https://www.udemy.com/blog/java-abstract-class/
public int getEmpId() {
return EmpId;
}
public void setEmpId(int empId) {
this.EmpId = empId;
}
}
design employee class
public class Design extends Employee {
public double rate;//rate for each hours
public double h;//hours worked
public Design(String fName, String lName, String pos) {
// TODO Auto-generated constructor stub
//double firstParam, int secondParam, int empNum
super(fName, lName, pos);
//toString();
calculateWeeklyPay();
}
#Override
public double calculateWeeklyPay() {
// TODO Auto-generated method stub
double weeklyPay = 0;
if (h <= 40) {
weeklyPay = h * rate;
}
if (h > 40) {
h = h * (3 / 2);
weeklyPay = h * rate;
}
//System.out.println(weeklyPay);
return weeklyPay;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
}
sales employee
public class Sales extends Employee {
private double weekSales;
private final double pay = 250;
private final double percent = .057;
public Sales(String fName, String lName, String pos) {
// TODO Auto-generated constructor stub
super(fName, lName, pos);
this.calculateWeeklyPay();
}
#Override
public double calculateWeeklyPay() {
// TODO Auto-generated method stub
double weekPay;
weekPay = pay + percent * this.getWeekSales();
return weekPay;
}
public double getWeekSales() {
return weekSales;
}
public void setWeekSales(double weekSales) {
this.weekSales = weekSales;
}
}
and i have two other employee type of classes but they won't be needed here since if i fix the problem in this one class i can fix the others.
here's is my company class which reads a file a calculates the weekly pay and total weekly pay of all employees classes
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Company implements CompanyInterface {
//private Employee addEmp = new Employee();
// private Position addPosition = new
private ArrayList<Employee> list;
private static int numberOfCompanies;
private String CompanyName;
private int numDesign;
private int numEmployees;
private int numManufacturing;
private int numManager;
private int numSales;
/*String fName="";
String lName="";
String position="";
String first="";
String second="";
String empID="";
Scanner File;*/
//private ArrayList<Employee> list2 ;
private Employee addEmp;
/**
* #param cn is the company name
*/
public Company(String cn) {
cn = "Wacky Widgets";
list = new ArrayList<Employee>();
numDesign = 0;
numEmployees = 0;
numManufacturing = 0;
numSales = 0;
numberOfCompanies++;
setCompanyName(cn);
}
#Override
/**
* #param fName first name
* #param lName last name
* #param pos position
* #return null if everything is right
*/
public String addEmployee(String fName, String lName, String pos,
double firstParam, int secondParam, int empNum) {
String message = null;
// if (pos.equals("DESIGN")&&
numDesign == 1 && numSales != 2 && numManufacturing != 4)
if (pos.equals("Design")) {
if (numDesign == 2)//p2=Position.DESIGN;
{
message = "There are already 2 design persons\nEmployee not
added ";
} else {
addEmp = new Design(fName, lName, pos);
numDesign++;
numEmployees++;
list.add(addEmp);
}
}//else return message;
//if (pos.equals("SALES")&&numDesign<1&&numSales<2&&numManufacturing<4)
else if (pos.equals("Sales")) {
if (numSales == 1) {
message = "There is already a sales person\nEmployee not
added ";
} else {
//p2=Position.SALES;
addEmp = new Sales(fName, lName, pos);
numSales++;
numEmployees++;
list.add(addEmp);
}
}//else return message;
else if (pos.equals("Manufacturing")) {
if (numManufacturing == 4) {
message = "There are already four manufacturing persons
\nEmployee not added ";
} else {
//p2=Position.MANUFACTURING;
addEmp = new Manufacturing(fName, lName, pos);
numManufacturing++;
numEmployees++;
list.add(addEmp);
}
} else if (pos.equals("Manager")) {
if (numManager == 1) {
message = "There is already a manager person\nEmployee not
added ";
} else {
//p2=Position.MANUFACTURING;
addEmp = new Manufacturing(fName, lName, pos);
numManager++;
numEmployees++;
list.add(addEmp);
}
}
//String str=fName+" "+lName+" "+pos+" "+firstParam+" "+empNum;
System.out.println(fName + " " + lName + " " + pos + " " + firstParam + " " + secondParam + "
"+empNum);
//firstParam=Employee.
System.out.println(calculateTotalWeeklyPay());
return message;
}
/**
* Returns number of companies
*
* #return number of companies
*/
public static int getNumCompanies() {
return numberOfCompanies;
}
public void setNumCompanies(int nc) {
numberOfCompanies = nc;
}
/**
* Sets the number of employees
*
* #param ne number of employees
*/
public void setNumemployees(int ne) {
numEmployees = ne;
}
/**
* Returns the number of employees
*
* #return the number of employees
*/
public int getNumEmployees() {
return numEmployees;
}
#Override
public int getNumManager() {
return numManager;
}
/**
* sets the number of designer
*
* #param nd number of designer
*/
public void setNumDesign(int num) {
numDesign = num;
}
#Override
public int getNumDesign() {
return numDesign;
}
public void setNumsales(int num) {
numSales = num;
}
#Override
public int getNumSales() {
return numSales;
}
/**
* Sets the number of manufacturer
*
* #param nm the number of manufacturer
*/
public void setNumManufacturing(int num) {
numManufacturing = num;
}
#Override
public int getNumManufacturing() {
return numManufacturing;
}
public void setNumManager(int num) {
numManager = num;
}
#Override
public String generateWeeklyReport() {
int empID = 0;
String title = "WEEKLY PAY REPORT FOR " + getCompanyName() + " COMPANY" + "\n";
String label = "Employee\n";
String label2 = "WEEKLY PAY \n";
int payWeek = 0;
double total = 0.0;
for (Employee index : list) {
empID += index.getEmpId();
payWeek += index.calculateWeeklyPay();
}
return title + label + empID + "\n" + "\t" + label2 + payWeek + "\n" + "Total Payroll:
$ "+total+"\n "+
"Total number of managers paid:" + getNumManager() + "\n" +
"Total number of Design Employees paid:" + getNumDesign() + "\n" +
"Total number of Sales Employees paid:" + getNumSales() + "\n" +
"Total number of Manufacturing Employees paid:" + getNumManufacturing();
}
#Override
public double calculateTotalWeeklyPay() {
double total = 0;
for (int index = 0; index < list.size(); index++) {
total = list.get(index).calculateWeeklyPay();
//total.add(list.get(index).calculateWeeklyPay());
}
return total;
}
/**
* #return str the arraylist of employees and positions
*/
public String printCompany() {
// TODO Auto-generated method stub
String str = "";
for (int index = 0; index < list.size(); index++) {
str += list.get(index).getFName() + " " + list.get(index).getLName() + "
"+" Position:
"+list.get(index).getPosition()+"\n ";
}//System.out.println(str);
return str;
}
/**
* #return company name
*/
public String getCompanyName() {
return CompanyName;
}
public void setCompanyName(String companyName) {
//companyName="Wacky Widgets";
this.CompanyName = companyName;
}
public String toString() {
// int i =0;
String str = CompanyName + "";
//String str = "";
for (int i = 0; i < list.size(); i++) {
str += "\n" + list.get(i).getFName() + " " + list.get(i).getLName() + "
"+" Position:
"+list.get(i).getPosition()+"\n ";
}
return str;
}
}
This stands out:
h = h * (3 / 2);
You're doing integer division here, so you're always multiplying by 1, effectively.
Change that to use floating-point values instead.
h = h * (3.0 / 2);
Alternatively, be explicit about what you're multiplying by - you know it's always time and a half, so I see no reason not to do this:
h = h * 1.5;

Categories

Resources