Constructor cannot be applied - java

i was doing this tutorial on Android Studio Development Essentials 6th Edition, the tutorial was about SQLiteDatase so i wrote evrything but i kept on getting an error whenever i try calling the Product Constructor everything is correct on the book but i cant get it right, this is the find Product Constructor and my Product class.
Find product
public Product findProduct(String productname) {
String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " +
COLUMN_PRODUCTNAME + " = " + productname + ";";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Product product = new Product();// Cannot be applied
if (cursor.moveToFirst()) {
cursor.moveToFirst();
product.setId(Integer.parseInt(cursor.getString(0)));
product.setProductName(cursor.getString(1));
product.setQuantity(Integer.parseInt(cursor.getString(2)));
cursor.close();
} else {
product = null;
}
db.close();
return product;
}
My Product Class
public class Product {
private int id;
private String ProductName;
private int Quantity;
public Product(int _id, String _productname, int _quantity) {
this.id = _id;
this.ProductName = _productname;
this.Quantity = _quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return ProductName;
}
public void setProductName(String productName) {
this.ProductName = productName;
}
public int getQuantity() {
return Quantity;
}
public void setQuantity(int quantity) {
this.Quantity = quantity;
}
}
Thank you.

public Product(int _id, String _productname, int _quantity) {
is the only constructor in you Product class definition (you don't have any others), so you have to call its constructor with these 3 parameters - instead of
Product product = new Product();// Cannot be applied
use something as
Product product = new Product(132, "Wheel", 1000);
Another solution:
Add another constructor in your Product class besides existing one, e. g. an empty one:
public Product() {}
(it may be located before or after your existing one).

If You created Your own constructor, the default one is not generated. Please take a look at Java default constructor
Regards

Related

How do I sort elements of 2 lists by their id which have been merged?

I have merged the above list but need to sort it based on the id param. How do I do that in the easiest and the optimal way possible?
I have a set of 2 users which I initially merged and now I would like to sort them based on their id and then display the results. Any ideas?
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Employee {
public String name;
public int id;
Employee(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
class Person {
public String name;
public int id;
Person(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
public class Solution {
public static void main(String[] args) {
List<Employee> employee = generateEmployees();
List<Person> persons = generatePersons();
ArrayList<Object> merged = new ArrayList<Object>(employee);
merged.addAll(person);
System.out.println("merged:"+merged +"\n");
for(int i=0;i<users.size();i++){
if(person.get(i).id<=5){
System.out.println("UserName:"+person.get(i).name+"\n");
}
}
for(int i=0;i<employee.size();i++){
if(employee.get(i).id<=5){
System.out.println("DesignerName:"+employee.get(i).name+"\n");
}
}
});
}
Thanks in advance!
I have looked at several methods online for sorting but couldnt figureo ut which was the best way to use it.Just want to display results once its sorted
User and Designer must extend from one same class. (or Designer extand user).
Then you create a Comparator (javadoc) and you use merged.sort (myComparator) (javadoc)
[EDIT]
class MyComparator implements Comparator<User> {
#Override
public int compare(User o1, User o2) {
return Integer.compare(o1.id, o2.id);
}
}
public class User {
public String name;
public int id;
User(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
public class Designer extends User{
Designer(String enter code herename, int id) {
super(name, id);
}
}
public class Solution {
public static void main(String[] args) {
...
ArrayList<User> merged = new ArrayList<User>(designers);
merged.addAll(users);
merged.sort(new MyComparator());
...
}
}
Assuming that you have list of User that is called users:
users.stream().sorted(Comparator.comparing(User::getId)).forEach(System.out::println);

How to get a specific value in Mongodb using Java?

In command prompt I enter the following:
db.products.insert( { item: "card", qty: 15 } )
I wanted to know how would I be able to get the item value from java.
I want to create a variable called item and it would know the value of it which is "card".
I am currently using MongoOperations in java but I do not know how to get only one value from MongoDB.
Pojo
#Document(collection="products")
public class ValueServerModel{
#Id
private String id;
String item;
int qty;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Product(String item, int qty) {
//super();
this.item = item;
this.qty = qty;
}
#Override
public String toString() {
return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
}
}
//provided by suwal
Long Shot Attempt
#Autowired
MongoOperations mongoOperations;
#PostConstruct
public List<SomeModel> getList() {
List<SomeModel> pmLst = mongoOperations.findAll(ServerModel.class);
//code above works I get a list of values based on mongo db
//attempting to retrieve one value, (stuck)
String value = mongoOperations.find("test", ValueServerModel.class);
With command prompt
I am able to get a value by using the following command:
db.products.find({}, {qty:0, _id:0})
//output ("item": "card")
I want to achieve the following:
db.products.find({}, {item})
//output should be "card".
is it possible to do what I just did above?
You can use projection to request the fields.
Something like
Query query = new Query();
query.fields().include("item").exclude("_id");
Product product = mongoOperations.findOne(query, Product.class);
This will populate the product pojo with item field.
You can use native mongo java driver to request the fields directly.
Something like
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase(db_name);
MongoCollection<Document> collection = database.getCollection(collection_name);
String value = collection.find().projection(Projections.include("item")).first().getString("item");
I get that you want to get the value, but you are not specifying based on what. That is "what is your query condition". Also not sure what ServerModel and ValueServerModel classes are, but let see if this general idea helps you.
Lets say you have following structure stored after your insert query in the collection products
{
"_id" : ObjectId("5939d5a1d0ffa3f0209fd42f"),
"item" : "card",
"qty" : 15
}
You will need a model representing the collection,
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="products") //this is what binds this class to your collection
public class Product {
#Id
private String id;
String item;
int qty;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Product(String item, int qty) {
//super();
this.item = item;
this.qty = qty;
}
#Override
public String toString() {
return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
}
}
Now in your code you would have something like this,
// findOne returns you single instance of an object of the specified type
Product product = mongoOperation.findOne(
new Query(Criteria.where("item").is("card")), Product.class);
System.out.println(product); //Output => Product [id=5939d5a1d0ffa3f0209fd42f, item=card, qty=15]
String value = product.getItem();
System.out.println("value is " + value);//Output => card
Lets say you want to get by id instead, so you would have something like this
Product product2 = mongoOperation.findOne(
new Query(Criteria.where("_id").is("5939d5a1d0ffa3f0209fd42f")),
Product.class);
System.out.println(product2);

Array is just printing out last element [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having this error where it prints out just the last element entered, prints out it the same amount of times as there are elements that are supposed to be in the array.
I have tested it with a System.out.println and the elements that are being added appear to be correct. How do I fix this error?
package stock.control.system;
import java.util.*;
public class StockArrayList implements StockList {
private ArrayList<StockItem> StockItems;
private int index = 0;
private int update;
private int counter = 0;
public StockArrayList() {
StockItems = new ArrayList<StockItem>(counter);
}
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
#Override
public String formatStockList(){
String temp = StockItem.format();
for (StockItem items : StockItems) {
temp = temp + items.arrayFormat() + "\n";
}
return temp;
}
}
The main method:
public class StockArrayListTester {
public static void main(String[] args) {
StockArrayList Stock = new StockArrayList();
Stock.addItem(new StockItem("P123","1TB Hard drive",75.00,267,50));
Stock.addItem(new StockItem("P125","i7 6800HQ Processor",257.00,113,45));
Stock.addItem(new StockItem("P129","i5 500HQ Processor",127.00,10,45));
Stock.deleteItem("P129");
System.out.printf(Stock.formatStockList());
}
}
the stock item class
package stock.control.system;
import java.util.*;
public class StockItem {
private static String itemID; // Five alpha-numeric characters
private static String itemDesc; // Item description
private static double price; // Item price in pounds sterling
private static int quantity; // Quantity in stock
private static int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}
#Override
public String toString() {
String toString ="[Item ID = " + this.itemID + ", Item Description = " +
this.itemDesc + ", Price = " + this.price + ", Quantity = " +
this.quantity + ", Re Order Level = " + this.reOrderLevel + "]";
return toString;
}
public static String format() {
String format = " STOCK ITEMS"
+ String.format("\n%-10s%-30s%-10s%-12s%-14s%-10s%-30s%-10s%-12s%-14s\n",
"ItemID","Item Description",
"Price","Quantity", "Re Order Level", "\n******",
" ****************"," *****", " ********",
" **************");
return format;
}
public String arrayFormat() {
return String.format("%-10s%-30s%-10s%-12s%-14s",
StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
}
public static String getItemID(){
return itemID;
}
public static String getItemDesc() {
return itemDesc;
}
public static double getPrice() {
return price;
}
public double setPrice(double price) {
this.price = price;
return price;
}
public static int getQuantity() {
return quantity;
}
public int setQuantity(int quantity) {
this.quantity = quantity;
return quantity;
}
public static int getReOrderLevel(){
return reOrderLevel;
}
public int setReOrderLevel(int reOrderLevel){
this.reOrderLevel = reOrderLevel;
return reOrderLevel;
}
}
The output I get is:
STOCK ITEMS
ItemID Item Description Price Quantity Re Order
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
BUILD SUCCESSFUL (total time: 0 seconds)
As a rule, never set static fields in a constructor. It is almost certainly a bug. IMHO, this should be a compiler error but it's not.
In this case, you are expecting each instance of StockItem to be different, however by making the fields static you are ensuring there is only one copy, only one value for those fields. I suggest you make them instance fields.
public class StockItem {
private final String itemID; // Five alpha-numeric characters
private final String itemDesc; // Item description
private double price; // Item price in pounds sterling
private int quantity; // Quantity in stock
private int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}
It's been a little while since I've used Java but it seems weird that in your addItem() method in your StockList class that you pass in a parameter 'item' but then never use it inside the method.
Why are you trying to "get" all of the properties of the stock item to add when you are passing them in to the function as a StockItem object?
Guess something is wrong here:
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(), StockItem.getPrice(), StockItem.getQuantity(), StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
All those getters are static methods. It does not make sense to me since I would think you want to get instance variables belonging to different objects. You must have initialiazed the StockItem class instance variables with the values printed out, otherwise I do not think your code would even compile.
Anyway why not adding the item passed as a parameter directly to the stock list?
Like so:
#Override
public void addItem(StockItem item) {
StockItems.add(counter, item);
counter++;
}

How to sort a link list based on a field of an object placed on the link list? [duplicate]

public class Product implements Serializable{
private String id;
private String name;
private double price ;
private int quantity;
public Product(String id, String name, double price, int quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return "Product{" + "id=" + id + ", name=" + name + ", price=" + price + ", quantity=" + quantity + '}';
}
I want to sort ArrayList<Product> by price and name. I search Google for a long time but I cann't solve it. Whether it can have problem with Serializable
You need to implement Comparable or Comparator interface for your purpose. sorting user defined objects with Comparator and sorting user defined objects with comparable
You can learn the difference between these two by reading these tutorials
Consider you want your products to be sorted using its price then make your Product implement Comparable as follows
public class Product implements Comparable<Product>{
public int compareTo(Product other){
// your logic here
}
}
But hold on... now that we have already implemented Comparable interface to sort the objects using its price, how can we sort them using another sort sequence? We only have one compareTo() method and we can't write separate sort sequence in the same class. Here comes the role of Comparator. With Comparator, you can define multiple sort sequences.
Suppose we want to sort using its price, then:
public class PriceSorter implements Comparator<Product>{
public int compare(Product one, Product another){
int returnVal = 0;
if(one.getPrice() < another.getPrice()){
returnVal = -1;
}else if(one.getPrice() > another.getPrice()){
returnVal = 1;
}else if(one.getPrice() == another.getPrice()){
returnVal = 0;
}
return returnVal;
}
}
and you want another sort sequence, now for its name, then:
public class NameSorter implements Comparator<Product>{
public int compare(Product one, Product another){
return one.getName().compareTo(another.getName());
}
}
Now, when you want to sort using price, then
Collections.sort(yourList,new PriceSorter());
If you want to sort using name, then
Collections.sort(yourList, new NameSorter());
The second argument takes the Comparator instance which makes the sort method know what logic to follow while sorting objects
Have the Product class implement the Comparable interface.
public class Product implements Serializable, Comparable<Product> {
//Ommitted constructors, fields and accessors
//This is an ascending sort order
#Override
public int compareTo(Product o) {
int result = this.name.compareToIgnoreCase(o.name);
if(result != 0){
return result;
}else{
return new Double(this.price).compareTo(new Double(o.price));
}
}
}
Then sorting is as easy as pass the List to Collections.sort():
public static void main(String[] args) {
Product p1 = new Product("p1", "shoes", 30.33, 20);
Product p2 = new Product("p2", "shoes", 20.30, 20);
Product p3 = new Product("p3", "shoes", 50.33, 20);
Product p4 = new Product("p4", "socks", 10.50, 20);
Product p5 = new Product("p5", "socks", 5.40, 20);
Product p6 = new Product("p6", "socks", 2.34, 20);
List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);
System.out.println("Unsorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
Collections.sort(products);
System.out.println("sorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
}
Here is the full source for Product that implements Comparable with a sort example in the main method:
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Product implements Serializable, Comparable<Product> {
private String id;
private String name;
private double price;
private int quantity;
public Product(String id, String name, double price, int quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return "Product{" + "id=" + id + ", name=" + name + ", price=" + price
+ ", quantity=" + quantity + '}';
}
#Override
public int compareTo(Product o) {
int result = this.name.compareToIgnoreCase(o.name);
if(result != 0){
return result;
}else{
return new Double(this.price).compareTo(new Double(o.price));
}
}
public static void main(String[] args) {
Product p1 = new Product("p1", "shoes", 30.33, 20);
Product p2 = new Product("p2", "shoes", 20.30, 20);
Product p3 = new Product("p3", "shoes", 50.33, 20);
Product p4 = new Product("p4", "socks", 10.50, 20);
Product p5 = new Product("p5", "socks", 5.40, 20);
Product p6 = new Product("p6", "socks", 2.34, 20);
List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);
System.out.println("Unsorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
Collections.sort(products);
System.out.println("sorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
}
}
Use a Comparator<Product>, here implemented anonymously (suitable for java 7 and earlier):
List<Product> list;
Collections.sort(list, new Comparator<Product>() {
public int compare(Product a, Product b) {
if (a.getPrice() == b.getPrice())
return a.getName().compareTo(b.getName());
return a.getPrice() > b.getPrice() ? 1 : a.getPrice() < b.getPrice() ? -1 : 0
}
});
Java 8 has a much cleaner way of achieving the above:
Collections.sort(list, Comparator.comparing(Product::getPrice).thenComparing(Product::getName));
If this defines the "natural order" of your products, consider making Product implement Comparable<Product> and implement it in the compareTo() method of Product.
You need to implement the Comparable interface. The interface requires you to add a function called compareTo(Product other) within which you write the code that checks the custom fields you want the objects to be compared by.
Alternatively you can do what #Prasad Kharkar suggested and write a Comaparator that essentially does the same thing.
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
As far as I know , you dont have such methods , what you can do is ; extend a subclass of Collection and add methods to sort (search or techniques like bubble sort,and more)
If you have facility for a database (more overhead)
*you could put it in there and use order by
*if you are using JPA , just dump your list into a entity class

How to compare Objects attributes in an ArrayList?

I am fairly new to Java and I have exhausted all of my current resources to find an answer. I am wondering if it possible to access an Objects first property to see if it matches a particular integer?
For example, I am trying to obtain a Product that is within my Database by searching for it by it's Product ID. Therefore, if I create two products such as, Product ipad = new Product(12345, "iPad", 125.0, DeptCode.COMPUTER); and Product ipod = new Product(12356, "iPod", 125.0, DeptCode.ELECTRONICS); (I have included this Product class below), and add them to an Arraylist such as, List<Product> products = new ArrayList<Product>(); how can I loop through this ArrayList in order to find that product by its ID?
This is the method I am working on:
List<Product> products = new ArrayList<Product>();
#Override
public Product getProduct(int productId) {
// TODO Auto-generated method stub
for(int i=0; i<products.size(); i++){
//if statement would go here
//I was trying: if (Product.getId() == productId) {
System.out.println(products.get(i));
}
return null;
}`
I know that I can include a conditional statement in the for loop but I cant figure out how to access the getId() method in the Product class to compare it the productId parameter?
package productdb;
public class Product {
private Integer id;
private String name;
private double price;
private DeptCode dept;
public Product(String name, double price, DeptCode code) {
this(null, name, price, code);
}
public Product(Integer id, String name, double price, DeptCode code) {
this.id = id;
this.name = name;
this.price = price;
this.dept = code;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public DeptCode getDept() {
return dept;
}
public void setDept(DeptCode dept) {
this.dept = dept;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
String info = String.format("Product [productId:%d, name: %s, dept: %s, price: %.2f",
id, name, dept, price);
return info;
}
}
Please let me know
You have already got the Product out of the List<Product> in the following statement:
System.out.println(products.get(i));
Now, that you have got Product, now to get it's id, you can just call it's getId() method:
if (product.get(i).getId() == productId) {
// Return this product.
}
I would also suggest you to use enhanced for-loop instead of the traditional loop like this:
for (Product product: products) {
// Now you have the product. Just get the Id
if (product.getId() == productId) {
return product;
}
}
Also, you should change the type of productId from Integer to int. You don't need a wrapper type there.
Have you considered using a HashMap (or LinkedHashMap) instead of an Array. This way you can use the productId as the key and the product as the value?
This will let you get the object without having to loop through the entire array.
For comparing the ArrayList Objects make override equal function in your CustomObject Class Like Employee.
ArrayList<Employee> list;
Employee emp;
//suppose you have some number of items in that list and emp object contains some value.
int size=list.size();
for(int i=0;i<size;i++) {
if(list.get(i).equals(emp)) {
//todo perform operation on the basis of result.
}
}
And suppose this is your Employee class and in that class you need to override the equal function.
class Employee{
int age;
String name;
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public void setAge(int emp_age) {
this.age=emp_age;
}
public void setName(String emp_name) {
this.name=emp_name;
}
#Override
public boolean equal(Employee emp) {
boolean isEqual=false;
if(emp!=null && emp instanceof Employee) {
isEqual=(this.age==emp.age);
}
return isEqual;
}
}
I hope this solution will help you to check for equal values and compare the values.
Thanks
According to your commented line //I was trying: if (Product.getId() == productId) I think where you were falling over is using Product (capital P). What you needed was:
if (products.get(i).getId() == productId)
Also, you weren't returning the product you found...
The problem with that form is that a) you have to find the product in the list twice (once in the condition and then again when printing the result - a third time if you returned the product) and b) it will throw a null pointer exception if the product you are looking for is not in the list.
This is a nicer, more compact way of doing it:
#Override
public Product getProduct(int productId)
{
for(Product product : products)
{
if (productId == product.getId())
{
System.out.println(product.toString());
return product;
}
}
return null;
}

Categories