I have officially come to the end of my rope. I cannot find what I did wrong. I have done this program almost exactly like another program I wrote a few days ago but I am having problems compiling. I do not know why I am getting errors on the output lines. Please help:
THIS IS THE RUNNING FILE:
package inventory1;
import java.util.Scanner;
public class RunApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DataCollection theProduct = new DataCollection();
String Name = "";
double pNumber = 0.0;
double Units = 0.0;
double Price = 0.0;
while (true) {
System.out.print("Enter Product Name: ");
Name = input.next();
theProduct.setName(Name);
if (Name.equalsIgnoreCase("stop")) {
return;}
System.out.print("Enter Product Number: ");
pNumber = input.nextDouble();
theProduct.setpNumber(pNumber);
System.out.print("Enter How Many Units in Stock: ");
Units = input.nextDouble();
theProduct.setUnits(Units);
System.out.print("Enter Price Per Unit: ");
Price = input.nextDouble();
theProduct.setPrice(Price);
System.out.print("\n Product Name: " + theProduct.getName());
System.out.print("\n Product Number: " + theProduct.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theProduct.getUnits());
System.out.print("\n Price per Unit: " + theProduct.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f\n\n\n", theProduct.getName(), theProduct.calculatePrice());
}
}
}
THIS IS THE DATA COLLECTIONS FILE:
package inventory1;
public class DataCollection {
String productName;
double productNumber, unitsInStock, unitPrice, totalPrice;
public DataCollection() {
productName = "";
productNumber = 0.0;
unitsInStock = 0.0;
unitPrice = 0.0;
}
// setter methods
public void setName(String name) {
productName = name;
}
public void setpNumber(double pNumber) {
productNumber = pNumber;
}
public void setUnits(double units) {
unitsInStock = units;
}
public void setPrice(double price) {
unitPrice = price;
}
// getter methods
public void getName(String name) {
productName = name;
}
public void getpNumber(double pNumber) {
productNumber = pNumber;
}
public void getUnits(double units) {
unitsInStock = units;
}
public void getPrice(double price) {
unitPrice = price;
}
public double calculatePrice() {
return (unitsInStock * unitPrice);
}
}
The reason why it doesn't compile is because your main code:
System.out.print("\n Product Name: " + theProduct.getName());
System.out.print("\n Product Number: " + theProduct.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theProduct.getUnits());
System.out.print("\n Price per Unit: " + theProduct.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f\n\n\n", theProduct.getName(), theProduct.calculatePrice());
Requires getName() But your getName() implementation did not exist. You didn't have the proper signature. Change it to a proper getter and it should work. Same goes for the other getters.
Instead of:
// getter methods
public void getName(String name) {
productName = name;
}
public void getpNumber(double pNumber) {
productNumber = pNumber;
}
public void getUnits(double units) {
unitsInStock = units;
}
public void getPrice(double price) {
unitPrice = price;
}
Use:
// getter methods
public String getName() {
return productName;
}
public double getpNumber() {
return productNumber;
}
public double getUnits() {
return unitsInStock;
}
public double getPrice() {
return unitPrice;
}
I believe the problem is in the way you are reading the values. While it is safe to read Strings using Scanner.next() but for other data structures you might need to clear a new line character from your input stream before you actually read the value.
But this is only in theory because you have given virtually nothing about your problem.
Related
I am trying to write a code that takes vehicle names and such and stores them in an array of objects. I have Vehicle as the parent class with a toString that prints the name, brand and gallons of tank, the two subclasses of parent are bus and car. Car and Bus ask how many doors,wheels or passengers. When printing the array out after randomizing the order i only get the to Strings from the parent class to print out when the index of the array is of the parent class. What i want to print out is:
Vehicle 0:
name: car brand: something : tanksize: 15
Doors: 4 : Wheels 4
My code is below:
import java.util.*;
public class Q1 {
public static void main(String args[]){
Scanner kb = new Scanner(System.in);
Vehicle[] list = new Vehicle[3];
for(int i =0;i < list.length;i++){
int random = (int)(Math.random()*3);
if(random == 0){
System.out.println("What is the Name, brand and how big is the gas tank of the vehicle?");
String name = kb.next();
String brand = kb.next();
int gasTank = kb.nextInt();
Vehicle a = new Vehicle(name,brand,gasTank);
list[i] = a;
}
else if(random == 1){
System.out.println("How many doors and wheels does the car have");
int doors = kb.nextInt();
int wheels = kb.nextInt();
System.out.println("What is the Name, brand and how big is the gas tank of the car?");
String name = kb.next();
String brand = kb.next();
int gasTank = kb.nextInt();
Car a = new Car(doors,wheels,name,brand,gasTank);
list[i] = a;
}
else{
System.out.println("How many doors and wheels does the bus have?");
int doors = kb.nextInt();
int wheels = kb.nextInt();
System.out.println("What is the Name, brand and how big is the gas tank of the bus?");
String name = kb.next();
String brand = kb.next();
int gasTank = kb.nextInt();
Bus a = new Bus(doors,wheels,name,brand,gasTank);
list[i] = a;
}
}
printArray2(list);
}
public static void printArray(Vehicle[] list){
for(int i = 0; i< list.length; i++){
System.out.println("Vehicle "+ i);
System.out.println(list[i]);
System.out.println("___________");
}
}
public static void printArray2(Vehicle[] list){
for(int i = 0; i< list.length;i++){
System.out.println("Vehicle "+ i);
System.out.println(list[i].toString());
System.out.println("___________");
}
}
}
class Vehicle {
String name;
String brand;
int gasTank;
public Vehicle(){
this(" ", " ", 15);
}
public Vehicle(String name, String brand,int gasTank){
this.name = name;
this.brand = brand;
this.gasTank = gasTank;
}
public String getname(){
return name;
}
public String getbrand(){
return brand;
}
public int getgasTank(){
return gasTank;
}
public void setname(String name){
this.name = name;
}
public void setbrand(String brand){
this.brand = brand;
}
public void setgasTank(int gasTank){
this.gasTank = gasTank;
}
public double milesPerGallon(double miles, double gallonsUsed){
return miles / gallonsUsed;
}
public String toString(){
return " name: " + name + " Brand: " + brand + " Gallons in Tank: " + gasTank;
}
public double fillTank(double gallonsUsed){
return (gasTank - gallonsUsed);
}
}
class Car extends Vehicle{
int numOfdoors;
int numOfWheels;
public Car(){
this(2,4,"","",10);
}
public Car(int numOfDoors, int numOfWheels, String name, String brand, int gasTank){
this.numOfdoors = numOfDoors;
this.numOfWheels = numOfWheels;
super.name = name;
super.brand = brand;
super.gasTank = gasTank;
}
public int getnumOfdoors(){
return numOfdoors;
}
public int getnumOfWheels(){
return numOfWheels;
}
public void setnumOfdoors(int numOfdoors){
this.numOfdoors = numOfdoors;
}
public double milesPerGallon(double miles, double gallonsUsed){
return miles / gallonsUsed;
}
public String toString(){
return "The car has " + numOfWheels + " wheels and " + numOfdoors + " doors";
}
}
class Bus extends Vehicle {
int numOfWheels;
int numOfPassengers;
public Bus(){
this(1,8,"","", 50);
}
public Bus(int numOfWheels, int numOfPassengers, String name, String brand, int gasTank){
this.numOfWheels = numOfWheels;
this.numOfPassengers = numOfPassengers;
super.name = name;
super.brand = brand;
super.gasTank = gasTank;
}
public int getNumOfWheels(){
return numOfWheels;
}
public int getNumOfPassengers(){
return numOfPassengers;
}
public void setNumOfWheels(int numOfWheels){
this.numOfWheels = numOfWheels;
}
public void setNumOfPassengers(int numOfPassengers){
this.numOfPassengers = numOfPassengers;
}
public double milesPerGallon(double miles, double gallonsUsed){
return miles / gallonsUsed;
}
public String toString(){
return "The bus has "+ numOfWheels + " Wheels and " + numOfPassengers + " Passengers";
}
}
In your code you are overriding the toString method in child classes. While what I understand is that you want to print values from parent also along with child class. So your toString in child class should be like below, where you first call parent toString also.
#Override
public String toString() {
return super.toString() + "wheels " wheels + " doors " + numOfdoors ; // or something like this
}
I'm working on a project where I have to make an array of objects created from a text file. However whenever I run it, I get
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.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at CustomerList.main(CustomerList.java:16)
Even though the text file starts with an integer. Please look at my code and give me some insight into what I'm doing wrong.
This is part of the text file that I have to read from:
100
900 Amazon purchasing#amazon.com 20000.0 0.08
210 Nordstrom purchasing#nordstrom.com 50000.0 0.07
10 Rutgers purchasing#rutgers.edu 32000.0 education
520 Alamo purchasing#alamo.com 23000.0 0.05
1 Kean purchasing#kean.edu 158000.5 education
100 Allied purchasing#allied.com 85300.0 0.06
950 JoesInc purchasing#joesinc.com 999999.0 0.03
697 BostonU purchasing#tufts.edu 340020.23 education
310 TruckersInc purchasing#truckersinc.com 55000.0 0.10
820 Clothiers purchasing#clothiers.com 20044.0 0.05
849 RedCross purchasing#redcross.org 48900.2 non-profit
125 ChocolateRus purchasing#chocolate.com 3000.5 0.1
import java.util.*;
import java.math.*;
import java.text.*;
import java.io.*;
public class CustomerList {
public static void main(String[] args)throws IOException {
File f = new File("custy.txt");
Scanner in = new Scanner(f);
Customer[] obj = new Customer[1];
int count = 0;
while(in.hasNext() ){
int id = in.nextInt();
String name = in.next();
String email = in.next();
double balance = in.nextDouble();
obj[count] = new Customer (id, name, email, balance);
count++;
}
in.close();
for (int i = 0; i < count; i++)
System.out.println(obj[i]);
}
}
class Customer {
public int custId;
public String name;
public String email;
public double balance;
public Customer() {
this.custId = 0;
this.name = "";
this.email = "";
this.balance = 0.0;
}
public Customer(int custId, String name, String email, double balance) {
this.custId = custId;
this.name = name;
this.email = email;
this.balance = balance;
}
public int getId() {
return custId;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public double getBalance() {
return balance;
}
public void setName(String name) {
this.name = name;
}
public void setId(int custId) {
this.custId = custId;
}
public void setEmail(String email) {
this.email = email;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("$.00");
return custId + " " + dollar.format(balance) + name + " " + email + " ";
}
}class TaxExempt extends Customer {
public String exempt;
public TaxExempt() {
this.exempt = "";
}
public TaxExempt(int custId, String name, String email, double balance, String exempt) {
super(custId, name, email, balance);
this.exempt = exempt;
}
public String getExempt() {
return exempt;
}
public void setExempt(String reason) {
this.exempt = reason;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("$.00");
return custId + " " + name + " " + dollar.format(balance) + " " + email + " " + exempt;
}
}
class NonExempt extends Customer {
public double tax;
public double afterTax;
public NonExempt() {
this.tax = 0.0;
this.afterTax = 0.0;
}
public NonExempt(int custId, String name, String email, double balance, double tax) {
super(custId, name, email, balance);
this.tax = tax;
}
public double getTax() {
return tax;
}
public void setTax(double tax) {
this.tax = tax;
}
public void setAfterTax() {
this.afterTax = tax * balance;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("$.00");
String add = "%";
// System.out.println("Non Exempt: " );
return custId + " " + name + " " + dollar.format(balance) + " " + email + " " + tax + add + " "
+ dollar.format(afterTax);
}
}
Your error is somewhat related to this question: Scanner is skipping nextLine() after using next() or nextFoo()?
Note: Assuming you removed the first 100 in the file
Your app is crashing because when it gets to
double balance = in.nextDouble();
And tries to iterate one more time, there's nothing in that line for
int id = in.nextInt();
To read from, all you need is to include:
in.nextLine();
After
double++;
And you should get your desired output.
Complete code as example:
import java.util.*;
import java.math.*;
import java.io.*;
class Test {
public static void main(String[] args)throws IOException {
File f = new File("custy.txt");
Scanner in = new Scanner(f);
while(in.hasNext() ){
int id = in.nextInt();
String name = in.next();
String email = in.next();
double balance = in.nextDouble();
in.nextLine();
System.out.println(id + " " + name + " " + email + " " + balance);
}
in.close();
}
}
The above code prints:
900 Amazon purchasing#amazon.com 20000.0
210 Nordstrom purchasing#nordstrom.com 50000.0
10 Rutgers purchasing#rutgers.edu 32000.0
520 Alamo purchasing#alamo.com 23000.0
1 Kean purchasing#kean.edu 158000.5
100 Allied purchasing#allied.com 85300.0
950 JoesInc purchasing#joesinc.com 999999.0
697 BostonU purchasing#tufts.edu 340020.23
310 TruckersInc purchasing#truckersinc.com 55000.0
820 Clothiers purchasing#clothiers.com 20044.0
849 RedCross purchasing#redcross.org 48900.2
125 ChocolateRus purchasing#chocolate.com 3000.5
I have an ArrayList that contains objects. Each of the object has 3 values: String name, double price, int quantity. How to write method that will sum all doubles of objects and print the result. And also if int quantity>1, price will be multiplied by quantity.
Code that i wrote so far:
Product class
public class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public static Product createProduct(String name, double price, int quantity){
return new Product(name, price, quantity);
}
}
Product list class
import java.util.ArrayList;
import java.util.List;
public class ProductList {
private String name;
List<Product> newList;
public ProductList(String name) {
this.name = name;
this.newList = new ArrayList<>();
}
public boolean addNewProduct(Product product) {
if (findProduct(product.getName()) >= 0) {
System.out.println("Product is already on the list");
return false;
}
newList.add(product);
return true;
}
public boolean removeProduct(Product product) {
if (findProduct(product.getName().toUpperCase()) < 0) {
System.out.println("Product not found");
return false;
}
newList.remove(product);
return true;
}
private int findProduct(String productName) {
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
if (product.getName().equals(productName)) {
return i;
}
}
return -1;
}
public Product queryProduct(String name) {
int position = findProduct(name);
if (position >= 0) {
return this.newList.get(position);
}
return null;
}
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
sum += newList.get(i).getPrice();
}
return sum;
}
/*public boolean listProducts(){};
public boolean updateProduct(){};
*/
}
Simulation class:
public class Simulation {
private static Scanner scanner = new Scanner(System.in);
private static ProductList myProductList = new ProductList("My list");
private static void addNewProduct() {
System.out.println("Enter new product name: ");
String name = scanner.nextLine();
System.out.println("Enter new product price: ");
double price = scanner.nextDouble();
System.out.println("Enter new product quantity");
int quantity = scanner.nextInt();
Product newProduct = Product.createProduct(name, price, quantity);
if (myProductList.addNewProduct(newProduct) == true) {
System.out.println("New product added: " + name + " | price: " + price + " | quantity: " + quantity);
}
}
private static void removeProduct() {
System.out.println("Enter product name: ");
String name = scanner.nextLine().toUpperCase();
Product existingProduct = myProductList.queryProduct(name);
if (existingProduct == null) {
System.out.println("No such product");
return;
}
if (myProductList.removeProduct(existingProduct)) {
System.out.println("Sucessfully deleted product: " + existingProduct.getName());
} else {
System.out.println("Error deleting");
}
}
private static void printActions() {
System.out.println("Avaiable actions");
System.out.println("press: ");
System.out.println("0 - to shut down\n" +
"1 - to add new product\n" +
"2 - to remove product\n" +
"3 - to sum all products");
}
private static void sumProducts(){
myProductList.sumProducts();
}
public static void main(String[] args) {
printActions();
boolean quit = false;
while (!quit)
try {
System.out.println("\nEnter action: ");
int action = scanner.nextInt();
scanner.nextLine();
switch ((action)) {
case 0:
System.out.println("\nShutting down...");
quit = true;
break;
case 1:
addNewProduct();
break;
case 2:
removeProduct();
break;
}
} catch (InputMismatchException e) {
System.out.println("Bad key pressed, only values form 0 to 2 accepted");
scanner.nextLine();
}
}
}
Thanks in advance
You can do it in one line using Java 8.
public double sumProducts() {
return newList.stream().mapToDouble(product -> product.getPrice() * product.getQuantity()).sum();
}
If you use double to store the price, you will get incorrect answers when you try to add and multiply the values. For example, 0.1 + 0.2 is NOT the same double as 0.3. If you want accurate arithmetic for decimal numbers, you should use the BigDecimal class in place of double. If you don't do that, I can guarantee that your program will sometimes give wrong answers.
So you need to change your Product class as follows.
public class Product {
private String name;
private BigDecimal price;
private int quantity;
public Product(String name, BigDecimal price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public static Product createProduct(String name, BigDecimal price, int quantity){
return new Product(name, price, quantity);
}
}
You will also need to make corresponding changes in the code that calls the methods of this class.
Once you've done that, you can use the methods of the BigDecimal class to do arithmetic. It might look something like this.
public BigDecimal calculateTotalPrice() {
BigDecimal total = BigDecimal.ZERO;
for (Product product : newList) {
BigDecimal linePrice = product.getPrice().multiply(new BigDecimal(product.getQuantity()));
total = total.add(linePrice);
}
return total;
}
the sum of each product was missing multiply by its quantity.
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
sum += product.getPrice() * product.getQuantity();
}
return sum;
}
I am relatively new to java and learning to program, this being my 8th week at uni. I have been fiddling around with my code for the past day and I have been searching for the past hour or two for a similar question that could help answer my problem but have not found one that helps my particular situation, at least not that I could understand.
For an assignment, I have been asked to write a program with 3 classes(an interface, a store and a product class) and I have been going ok until I need to display data on the interface that is held in the product class. At the moment the code will compile fine but when I run the program and try to use the writeOutput() method I get a stack overflow error. Anyway this is what I have so far:
This is the method I am trying to get to work in the interface class:
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
And this is one of the methods from the store class:
public String getName()
{
return getName();
}
Finally I'll include the getter and setter from the product class just in case:
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
Hopefully this is enough information for someone to be able to help me but if it is not, I am happy to upload all three classes in their entirety.
Cheers Cale.
Edit: I have decided to add all three classes to help people who wish to help me (just keep in mind that I am nowhere near finishing and my code is probably riddled with problems) Hopefully it's not too messy for you guys to understand. And sorry for not writing many comments, it's something i need to work on :)
import java.util.*;
public class MatesInterface
{
Store matesStore = new Store();
private void run()
{
showInterface();
chooseOption();
}
private void showInterface()
{
System.out.println("What would you like to do?:");
System.out.println("(1)Input data for the product");
System.out.println("(2)Show data from one product");
System.out.println("(3)Show the replenishment strategy for a product");
System.out.println("(0)Exit the program");
}
private void chooseOption()
{
int option;
boolean flag = false;
Scanner console = new Scanner(System.in);
System.out.print("Please choose an option: ");
option = console.nextInt();
if(option==1)
{
readInput();
}
else if(option==2)
{
writeOutput();
}
else if (option==3)
{
}
else if(option==0)
{
}
else
{
flag = true;
}
while (flag)
{
System.out.println("That is not a valid option.");
System.out.println("Please choose an option: ");
option = console.nextInt();
flag = false;
}
}
private void readInput()
{
Store matesStore = new Store();
String name;
int productChoice, demandRate;
double setupCost, unitCost, inventoryCost, sellingPrice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1), (2) or (3): ");
productChoice = console.nextInt();
System.out.println("Please enter the product's name: ");
name = console.next();
System.out.println("Please enter the product's demand rate: ");
demandRate = console.nextInt();
System.out.println("Please enter the product's setup cost: ");
setupCost = console.nextDouble();
System.out.println("Please enter the product's unit cost: ");
unitCost = console.nextDouble();
System.out.println("Please enter the product's inventory cost: ");
inventoryCost = console.nextDouble();
System.out.println("Please enter the product's selling price: ");
sellingPrice = console.nextDouble();
matesStore.addData(productChoice, name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
chooseOption();
}
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
}
public static void main (String[] args)
{
MatesInterface intFace = new MatesInterface();
intFace.run();
}
}
public class Store
{
// instance variables - replace the example below with your own
private Product product1, product2, product3;
public Store()
{
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void addData(int option, String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
if (option==1) setData(product1, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else if (option==2) setData(product2, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else setData(product3, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
}
private void setData(Product product, String name, int demandRate, double setupCost, double unitCost, double inventoryCost, double sellingPrice)
{
product.setName(name);
product.setDemand(demandRate);
product.setSetup(setupCost);
product.setUnit(unitCost);
product.setInventory(inventoryCost);
product.setPrice(sellingPrice);
}
public String getName()
{
return getName();
}
}
import static java.lang.Math.*;
public class Product
{
private String name;
private int demandRate;
//private final int REPLENISHMENTRATE=0;
private double setupCost;
private double unitCost;
private double inventoryCost;
private double sellingPrice;
//Constructors for the class Product
public Product()
{
name = "No name yet.";
demandRate = 0;
unitCost = 0;
setupCost = 0;
inventoryCost = 0;
sellingPrice = 0;
}
public Product(String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
name = newName;
demandRate = newDemand;
unitCost = newUnit;
setupCost = newSetup;
inventoryCost = newInventory;
sellingPrice = newPrice;
}
// Accessor and mutator methods to access and modify data on a Product object
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDemand(int newDemand)
{
demandRate = newDemand;
}
public int getDemand()
{
return demandRate;
}
public void setUnit(double newUnit)
{
unitCost = newUnit;
}
public double getUnit()
{
return unitCost;
}
public void setSetup(double newSetup)
{
setupCost = newSetup;
}
public double getSetup()
{
return setupCost;
}
public void setInventory(double newInventory)
{
inventoryCost = newInventory;
}
public double getInventory()
{
return inventoryCost;
}
public void setPrice(double newPrice)
{
sellingPrice = newPrice;
}
public double getPrice()
{
return sellingPrice;
}
}
The method from the store class is recursivelly calling itself with no terminating clause, this is leading to StackOverflowError :
public String getName()
{
return getName(); // calls itself
}
Instead return the value of name variable if it exists in Store class, or whatever variable you want to be returned as a name:
public String getName()
{
// determine the product name you want
return myProduct.getName();
}
Basically i am trying to search for specif names in an Array-list and then remove just that name.I am doing an assignment for college, and it species to search and remove by name, so i cant use the int index of, I am fairly new to java, so ill post my code maybe I am missing something any help would be great.
import java.util.ArrayList;
public class GaaClub {
private ArrayList<Member> players;
{
}
public GaaClub() {
players = new ArrayList<Member>();
}
public void addStanderedMember() {
// create a message object:
StdOut.println("Please enter the members's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the members address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the members DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
Member player = new Member(name, address, dob, mempaid);
players.add(player);
}
public void addStandaredPlayer() {
// create a message object:
StdOut.println("Please enter the standard Player's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the standard Player's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the standard Player's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
StandardPlayer player = new StandardPlayer(name, address, dob, mempaid);
players.add(player);
}
public void addElitePlayer() {
// create a message object:
StdOut.println("Please enter the Elite Players's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the Elite Players's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the Elite Players's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the the amount to Pay: ");
double mempaid = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's BMI: ");
double bmi = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's height: ");
double height = StdIn.readDouble();
ElitePlayer player = new ElitePlayer(name, address, dob, mempaid, bmi,
height);
players.add(player);
}
public static void main(String[] args) {
GaaClub app = new GaaClub();
app.run();
}
public void memberType() {
StdOut.println("Enter Type of membership: ");
StdOut.println("1) Add a Standard Member");
StdOut.println("2) Add an Elite Player");
StdOut.println("3) Add a Standard Player");
String memberchoice = StdIn.readString();
if (memberchoice.equals("1"))
addStanderedMember();
if (memberchoice.equals("2"))
addElitePlayer();
if (memberchoice.equals("3"))
addStandaredPlayer();
}
public void listNames() {
for (Member player : players) {
player.list();
}
}
public void removeName() {
for (Member player : players) {
listNames();
String sResponse = StdIn.readString();
if (sResponse.equals(player.name))
{
players.remove(player);;
return;
}
}
}
private int mainMenu() {
StdOut.println("1) Add a Member");
StdOut.println("2) Remove Player");
StdOut.println("3) List Names");
StdOut.println("4) List Members");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
public void run() {
{
StdOut.println("Posts");
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
memberType();
break;
case 2:
removeName();
break;
case 3:
addStanderedMember();
break;
case 4:
listNames();
break;
}
option = mainMenu();
}
StdOut.println("Exiting...");
}
}
}
And Second file:
import java.util.ArrayList;
public class Member {
protected String name;
protected String address;
protected String dob;
protected double mempaid;
public Member(String name, String address, String dob, double mempaid) {
this.name = name;
this.address = address;
this.dob = dob;
this.mempaid = mempaid ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDob() {
return dob;
}
public void list(){
System.out.println(name);
}
public void setDob(String dob) {
this.dob = dob;
}
public double getMempaid() {
return mempaid;
}
public void setMempaid(double mempaid) {
this.mempaid = mempaid;
}
#Override
public String toString() {
return "Member [name=" + name + ", address=" + address + ", dob=" + dob
+ ", mempaid=" + mempaid + "]";
}
}
import java.util.ArrayList;
public class StandardPlayer extends Member {
private ArrayList<Competition> competition;
public StandardPlayer(String name, String address, String dob,
double mempaid) {
super(name, address, dob, mempaid);
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
public void setCopmetition(ArrayList<Competition> copmetition) {
this.competition = copmetition;
}
void addCompetiton(Competition c) {
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "StandardPlayer [competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
}
And third file:
import java.util.ArrayList;
public class ElitePlayer extends Member {
private double bmi;
private double height;
private ArrayList<Competition> competition;
public ElitePlayer(String name, String address,
String dob, double mempaid, double bmi, double height) {
super(name, address, dob, mempaid);
this.bmi = bmi;
this.height = height;
}
public double getBmi() {
return bmi;
}
public void setBmi(double bmi) {
this.bmi = bmi;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "ElitePlayer [bmi=" + bmi + ", height=" + height
+ ", competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
public void setCompetition(ArrayList<Competition> competition) {
this.competition = competition;`enter code here`
}
}
ArrayList has a method which can remove by Object:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
arr.remove("Bob");
it removes the first instance of the object.
You could of course simulate the same debavior:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).equals(searchTerm) {
arr.remove(i);
break;
}
}
This deviation from the built in method would only be recommended if you wanted to have the search delete on some other, or similar condition. For example if it contained the word "Bob"...
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob Bobingston");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(searchTerm)) {
arr.remove(i);
break;
}
}
It seems as if you already have a loop set-up for it. Just loop through the members, check if the name equals what you're looking for, then remove that member from the list if it is
for(Member mem : players) { //loop through each member in list
if(mem.getName().equalsIgnoreCase("name")) { //check if member's name is "name"
players.remove(mem); //removes member from list if it is
}
}
equalsIgnoreCase(String) checks the string without checking for case sensitivity. It won't care for capitalization. If you care about capitalization, use equals(String)