I'm trying to create a class that represents a person's name and that has fields representing the first name, middle initial, and last name, (also several methods).
When I try to run my code, I receive a Illegal modifier for the local class Name; only abstract or final is permitted error and cannot find a way to resolve this. Please help me resolve any errors so that my code will perform the desired (and commented) tasks. Thank you in advance.
public class Name {
String first_name;
String middle_initial;
String last_name;
//constructor that accepts first name, middle initial, and last name as parameters and initializes the Name object's state with those values
public Name(String first_name, String middle_initial, String last_name) {
first_name = "John";
middle_initial = "Q.";
last_name = "Public";
}
//method to return the person's name in first name, middle initial, and last name order.
public String getNormalOrder() {
String name = first_name + " " + middle_initial + " " + last_name;
return name;
}
//method to return the person's name in reversed order: last name, first name, and middle name.
public String getReverseOrder() {
String name = last_name + ", " + first_name + " " + middle_initial;
return name;
}
//method to return the full name in first, middle, last order, in String form
public String toString() {
return first_name + " " + middle_initial + " " + last_name;
}
public static void main(String[] arg){
first_name = "John";
middle_initial = "Q.";
last_name = "Public";
getNormalOrder();
getReverseOrder();
toString();
}
}
I suggest you start over with a file Name.java.
From the top, you can only have one public class of the same name as the file it is contained within.
public class Name {
}
Now, your field definitions are fine.
The constructor, however, should not hard-code the values of "John Q. Public", as this Name class can represent any instance of Name.
Therefore, you need to assign the fields using this, which is needed to "qualify" which variable you are using since they are the same variable names. (If you renamed String first_name here, to String fName, for example, then first_name = fName would be possible).
public Name(String first_name, String middle_initial, String last_name) {
this.first_name = first_name;
this.middle_initial = middle_initial;
this.last_name = last_name;
}
Then, in the main method, you want to make an instance of this object.
Name name = new Name("John", "Q.", "Public");
That's it.
But if you want to display those values, simply calling your methods isn't correct, as it needs to know which Name value to call the methods on. You also need to print the String values that are returned to even see them.
System.out.println(name.getNormalOrder());
System.out.println(name); // calls name.toString()
Related
I am getting an SQL exception
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as col_7_0_ from locales offerlocal0_ cross join offers offer2_ inner join offer' at line 1
While calling the repository method
#Query("SELECT DISTINCT new com.greenflamingo.staticplus.model.catalog.dto.OfferGet(ol.root.id,ol.title "
+ ",ol.description,dl.name,ol.root.price,ol.root.currency,ol.root.visible,ol.root.images) "
+ "FROM OfferLocale ol,DescriptorLocale dl "
+ "WHERE ol.root.webfront.id = (:webId) AND ol.culture.languageCode = (:langCode) "
+ "AND dl.culture.languageCode = (:langCode) "
+ "AND ol.root.category = dl.root")
Page<OfferGet> findAllWebfrontLocalized(#Param("webId")int webfrontId,#Param("langCode")String langCode,Pageable pageable );
I have narrowed the issue down to the Collection i am trying to pass to constructor (ol.root.images) . Tried with List (it gave me a constructor missmatch) and with Set (had the same error as shown here)
This is the bean i am using
public class OfferGet implements Serializable{
private static final long serialVersionUID = 6942049862208633335L;
private int id;
private String title;
private String shortDescription;
private String price;
private String category;
private boolean visible;
private List<Image> images;
public OfferGet(String title, String category) {
super();
..........
}
public OfferGet() {
super();
}
public OfferGet(int id, String title, String description
, BigDecimal price
,String currency,
boolean visible) {
.........
}
public OfferGet(int id, String title, String description,String category
, BigDecimal price
,String currency,
boolean visible,
Collection<Image> images) {
..........
}
}
I am using java 11, mariaDb and Springboot 2.0.5
Does anyone know why is this happening and if there is any way around it? Any help would be much appreciated, mustache gracias! :D
It's not possible to create an object with the constructor expression that takes a collection as argument.
The result of a SQL query is always a table.
The reason is that identification variables such that they represent instances, not collections.
Additionally you cannot return root.images you must join the OneToMany relationship and then you no longer have a collection but each attribute.
The result of the query will be cartesian product.
This is a correct query:
#Query("SELECT DISTINCT new com.greenflamingo.staticplus.model.catalog.dto.OfferGet(ol.root.id,ol.title "
+ ",ol.description,dl.name,ol.root.price,ol.root.currency,ol.root.visible, image) "
+ "FROM OfferLocale ol,DescriptorLocale dl "
+ "JOIN ol.root.images image
+ "WHERE ol.root.webfront.id = (:webId) AND ol.culture.languageCode = (:langCode) "
+ "AND dl.culture.languageCode = (:langCode) "
+ "AND ol.root.category = dl.root")
I have a named query that selects all the record that have a search string in it.
This is my NamedQuery.
#NamedQuery(
name = "findAllPersonBySearch",
query = "SELECT p FROM Person p "
+ "WHERE LOWER(p.pvId) LIKE LOWER(:searchString) "
+ "OR LOWER(p.firstName) LIKE LOWER(:searchString) "
+ "OR LOWER(p.middleName) LIKE LOWER(:searchString) "
+ "OR LOWER(p.lastName) LIKE LOWER(:searchString) "
+ "OR p.birthDate LIKE :searchString"
)
The record contains 2 enum in it. One is Gender and the Other is Person Type. Here are my enums:
PersonType
package ph.com.smesoft.hms.reference;
public enum PersonType {
Customer, Personnel
}
Gender
package ph.com.smesoft.hms.reference;
public enum Gender {
Male, Female
}
I have a search box in my list view which returns a string whenever the Search button is clicked.
How do I use the enums as parameters in my Named Query?
I have tried this:
ph.com.smesoft.hms.reference.PersonType.Personnel = :searchString
But nothing happened. Hope someone can help me out on this!
UPDATE:
This is where the method that accepts the string passed from the Controller and sets it as query parameter:
public List<Person> findAllBySearch(String searchString){
TypedQuery<Person> searchResult = em.createNamedQuery("findAllPersonBySearch", Person.class);
searchResult.setParameter("searchString",'%'+searchString+'%');
List<Person> result=searchResult.getResultList();
return result;
}
and this is my controller method that accepts the string typed from the view:
Controller Method
#RequestMapping(value = "/search", method = { RequestMethod.GET })
public String listofFloor(#ModelAttribute("SearchCriteria") SearchForm searchForm, Model uiModel) {
uiModel.addAttribute("people", personService.findAllBySearch(searchForm.getSearchString()));
return "people/list";
}
I get a ClassCastException when trying to query my JPA entity class. I only want json to show two columns. That is name and address. How do I only show selected columns in JPA? From debugging it has to be the for loop. So List is the object and I need to make the right side an object instead of a list correct?
Entity
#Entity
#Table(name = "Personnel")
public class User implements Serializable {
private String id;
private String name;
private String address;
public User(String id, String name, String address)
{
this.id = id;
this.name = name;
this.address = address;
}
#Id
#Column(name = "name", unique = true, nullable = false)
public String getName() {
return this.name;
}....
//setters getters
Query/Impl
public List<User> getRecords(User ent){
String sql = "select "
+ " usr.name, usr.address "
+ " from User usr"
+ " where usr.id = '1' ";
List<User> records = this.getSession().createQuery(sql).list();
for ( User event : records ) {
System.out.println( "Records (" + event.getName + ") );
}
return records;
}
Update
This is my attempt to declare the result object as List. Does the method have to be an object instead of ?
public List<User> getRecords(User ent){
String sql = "select "
+ " usr.name, usr.address "
+ " from User usr"
+ " where usr.id = '1' ";
Map<String, String> results = new HashMap<String, String>();
List<Object[]> resultList = this.getSession().createQuery(sql).list();
// Place results in map
for (Object[] items: resultList) {
results.put((String)items[0], (String)items[1]);
results.toString();
}
return (List<User>) results;
You can pass a DTO class to the SELECT clause like this:
List<UserDTO> resultList = this.getSession().createQuery("""
select
new my.package.UserDTO(usr.name, usr.address)
from User usr
where usr.id = :userId
""")
.setParameter("userId", userId)
.getResultList();
You should read the complete object:
String sql = " from User usr"
+ " where usr.id = '1' ";
Or declare the result object as List<Object[]>
You can use generic(I assure you are using java 1.5 and above) and and one you get result, you do type check and downcast to desired type.
If You don't want to read the complete object you have to use Criteria and Projection on specific properties.
See this answer it will help
Hey am trying to make a javafx program that join two strings but i am getting error when trying to join them with join command. My javafx code is
String name = "John";
String lastname= "doe";
String fullname = name.join(lastname);
I don't know this is correct or it's my foolishness to use this as i am beginner to javafx. I hope you can resolve my problem. Thanks in advance
String name = "John";
String lastname= "doe";
String fullname = String.join(" ", name, lastname);
As in the documentation:
public static String join(CharSequence delimiter, CharSequence... elements)
But you could simply use concatenation:
String fullname = name + " " + lastname;
I'm having some difficulty understanding the update command for SQLite.
In my example I am perform an update database, but if there's an error I'm delivering an error message. If the user trys to update a record that doesn't exist, I'm not getting an error message.
Here is my code, first the update command, and then my call:
public long updateContact(String firstName, String lastName, String address, String city, String state,
int zipCode, long mobileNumber, long altNumber, String email) {
ContentValues contactInfo = new ContentValues();
contactInfo.put(KEY_FNAME, firstName);
contactInfo.put(KEY_LNAME, lastName);
contactInfo.put(KEY_ADDR, address);
contactInfo.put(KEY_CITY, city);
contactInfo.put(KEY_STATE, state);
contactInfo.put(KEY_ZIP, zipCode);
contactInfo.put(KEY_MOBILE, mobileNumber);
contactInfo.put(KEY_ALT, altNumber);
contactInfo.put(KEY_EMAIL, email);
String where = "FIRSTNAME = '" + firstName + "' AND LASTNAME = '" + lastName + "'";
return db.update(DATABASE_TABLE, contactInfo, where, null);
}
The call:
if (searchTerm.length() > 0) {
id = db.updateContact(fName, lName, address.getText().toString().trim(),
city.getText().toString().trim(), state.getSelectedItem().toString().trim(), Integer.parseInt(zip.getText().toString().trim()),
Long.valueOf(mobile.getText().toString().trim()), Long.valueOf(alternate.getText().toString().trim()),
email.getText().toString().trim());
if (id == -1) {
DisplayErrorDialog("I'm sorry, we can not update the contact with the present data.");
}
}
The update is working when I give it valid data. But when I give it invalid data (name that isn't in the database), I'm not getting the appropriate error message.
From the fine manual:
Returns
the number of rows affected
So db.update will return 0 when nothing was updated (i.e. your where didn't match any rows) and that zero will be returned by updateContact. So you probably want to rename id to numberUpdated (or similar) and show on error on numberUpdated <= 0 instead of looking for a -1.
The return value is the number of rows updated, not the id. Check for 0, not -1. This implies you could be updating more than one record, which is how database updates work generally.