Multidimensional array condition in Java - java

I want to pun a condition in an multidimesional array and I'm stuck. My method should return a name in a specific format. If find a title like (Mr.,Mrs) return Title , first letter from name , and the full surname. If title is not found return full name + full surname. Eg. Ms. S. T. Mark or Smith T. Rose or Tony Mark.
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. ","Miss"},
{"Smith ", "Jones "},
{"Tony ", "Jhon "},
{"Mark ","Rose "}
};
if (names[0].equals(names)&& names[1].equals(names)&&names[2].equals(names)&& names[3].equals(names)){
return names[0][0] + names[1][0].substring(0,1)+". " + names[2][0].substring(0,1)+". "+names[3][0];}
return"";

As I wrote in the comment this doesn't make sense:
names[0].equals(names)
names[0] is string array (String[]) containing: {"Mr. ", "Mrs. ", "Ms. ","Miss"}
While names is array of string arrays (String[][]) containing everything, so you can't compare them in such way, it will always be false.
Moreover you actually shouldn't ever use equals for arrays. Please check this post for more information:
https://stackoverflow.com/a/8777266/7624937
Now, as suggested by #Tschallacka you should probably create Person class, e.g:
class Person {
String title;
String name;
String surname;
}
and then implement functions which are of your interest. So according to your description such function would look like this:
public String introduceYourself() {
if (title != null) {
return title + " " + name.charAt(0) + " " + surname;
} else {
return name + " " + surname;
}
}

Related

Saving List<T> as String

I've been trying to save a list of data as Strings, but when I try a method .toString on List, it returns address in memory instead of data.
public class Item {
Integer price = 20;
Integer modelNumber = 100;
String description = "Description";
String title = "Title";
Boolean wasBought = true;
}
public static void main(String[] args) {
List<Item> data = new ArrayList<>();
data.add(new Item());
System.out.println(data.toString());
}
You need to override toString function in your Item class. Add the following snippet into your Item class:
#Override
public String toString() {
return "Item{" +
"price=" + price +
", modelNumber=" + modelNumber +
", description='" + description + '\'' +
", title='" + title + '\'' +
", wasBought=" + wasBought +
'}';
}
Output:
[Item{price=20, modelNumber=100, description='Description', title='Title', wasBought=true}]
You can convert List to json format string by json utils, e.g. jackson or fastjson, in case you may need to convert it to Objects later.
Simply use Lombok (Add Lombok jar into classpath) #ToString annotate for Item class, it will do the needful output https://projectlombok.org/features/ToString

Why do I get, and how do I solve this "String to object of type <objecttype>" error

I am (being an absolute beginner), trying to create a simple tool, that creates some objects and links them.
The objects are:
Customers
Licenses (2 types, extends class)
The idea is to use (one of) the customer company name when creating a license, so the license is linked to a customer.
I use ArrayLists to store the data.
I tried to use the getter for Customer cCompany, but when I try to actually create a new license object, I get errors about incompatible types (String to object of type customer)
How can I fix that error?
Any help is highly appreciated, but please explain well, me being an absolute beginner. I probably overcomplicate stuff....
Some code extracts:
From Main:
public class Main {
public static void main(String[] args) {
//Create customers
List <Customer> customers = new ArrayList <> (10);
customers.add(new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
....
//Create Elvis licenses (based on superclass License)
List <ElvisLicense> ellicenses = new ArrayList <> (10);
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
Class: Customer:
class Customer {
String cCompany;
private String cName;
private int cPhone;
private String cEmail;
public Customer( String cCompany, String cName,int cPhone, String cEmail)
{
this.cCompany = cCompany;
this.cName = cName;
this.cPhone = cPhone;
this.cEmail = cEmail;
}
//This getter should be used to link the license to the customer (Done in License.java)
public String getcCompany() {
return cCompany;
}
Class License (Superclass)
class License {
// Used no modifier to set access for Class/Package and Subclass inside the package
Customer licenseCompany;
String lVendor;
int lContractNumber;
String lCertificateNumber;
String lProductName;
String lLicenseKey;
int lNumberOfSeats;
public License(Customer cCompany, String lVendor, int lContractNumber, String lCertificateNumber,
String lProductName, String lLicenseKey, int lNumberOfSeats)
{
licenseCompany = cCompany;
this.lVendor = lVendor;
this.lVendor = lVendor;
this.lContractNumber = lContractNumber;
this.lCertificateNumber = lCertificateNumber;
this.lProductName = lProductName;
this.lLicenseKey = lLicenseKey;
this.lNumberOfSeats = lNumberOfSeats;
}
public Customer getLicenseCompany() {
return licenseCompany;
}
public void setLicenseCompany(Customer licenseCompany) {
this.licenseCompany = licenseCompany;
}
//preparations to allow for example printing the content of an arraylist element
#Override
public String toString(){
return "Customer name " + getLicenseCompany() + "\n" + "Vendor name " + getlVendor() + "\n" + "Contract number: " + getlContractNumber() + "\n"
+ "Certificate number: " + getlCertificateNumber() + "\n" +
"Product name " + getlProductName() + "\n" + "Licence key: " + getlLicenseKey() + "\n"
+ "Number of seats: " + getlNumberOfSeats();
}
}
And the extended class:
public class ElvisLicense extends License{
private boolean elIsBundle;
private boolean elIsSubscription;
public ElvisLicense(
Customer licenseCompany,
String lVendor,
int lContractNumber,
String lCertificateNumber,
String lProductName,
String lLicenseKey,
int lNumberOfSeats,
boolean elIsBundle,
boolean elIsSubscription
)
{
super(
licenseCompany,
lVendor,
lContractNumber,
lCertificateNumber,
lProductName,
lLicenseKey,
lNumberOfSeats);
this.elIsBundle = elIsBundle;
this.elIsSubscription = elIsSubscription;
}
.....
#Override
public String toString(){
return "Customer name " + licenseCompany + "\n"
+ "Vendor name " + lVendor + "\n"
+ "Contract number: " + lContractNumber + "\n"
+ "Certificate number: " + lCertificateNumber + "\n"
+ "Product name " + lProductName + "\n"
+ "Licence key: " + lLicenseKey + "\n"
+ "Number of seats: " + lNumberOfSeats + "\n"
+ "Number of seats: " + elIsBundle + "\n"
+ "Number of seats: " + elIsSubscription;
}
}
I expect that the Customername is used when creating a new license.
Below line is wrong.
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
As license need customer object an parameter. Instead, you should create customer object first.
ellicenses.add(new ElvisLicense(new Customer("TestCompany","VendorA",1234,"1234-A"),"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
for reusing that customer list to avoid create company.
for(Customer customer : customers){
// here you need some way to offer other parameters except customer parameter.
License license = new new ElvisLicense(customer,"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true);
ellicenses.add(license);
}
What you need to do is to use one of the Customer objects you have already created when creating the ElvisLicense object. To more easily find that customer by name I suggest you store them in a map instead of a list with the name as a key.
Map<String, Customer> customerMap = new HashMap<>();
Customer customer = new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
customerMap.put(customer.getcCompany(), customer);
so when creating the license you look up the customer
List <ElvisLicense> ellicenses = new ArrayList <> (10);
Customer customer = customerMap.get("TestCompany");
if (customer != null) {
ElvisLicense license = new ElvisLicense(customer,"VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
ellicenses.add(license);
} else {
//If the customer isn't found you need some kind of error handling, better than below :)
System.out.println("Can't create a license, no customer found");
}

accessing list elements in java

I created a linkedlist object as follows
importBuffer = new BufferedReader(new FileReader(importcsvFile));
while ((line = importBuffer.readLine()) != null) {
// use comma as separator
String[] importedFile = line.split(cvsSplitBy); //cap,comune,provincia,stato
System.out.println("Codice Azienda " + importedFile[0] + " , Codice Cliente=" + importedFile[1] + " , Regione Sociale=" + importedFile[2] + " , Indrizzo=" + importedFile[3] + " , comune=" + importedFile[4] + " , provincia=" + importedFile[5] + " , stato=" + importedFile[6] +"]");
counter++;
PublicDefinition.importList.add(importBuffer.toString());
List customers = select.select(importedFile[0],importedFile[1], importedFile[3]);
if(!customers.isEmpty())
{
System.out.println("selected Customer : " + customers.size());
buffureList = customers;
Object a=List.class.cast(customers);
PublicDefinition.testingList.add(buffureList.toString());
System.out.println("selected Customer : " + PublicDefinition.importList.get(0));
System.out.println("selected Customer : " + PublicDefinition.testingList.getFirst());
updateCustomer = customers;
if(customers.get(0)==importedFile[0])
System.out.println("Matched Codice Azienda");
select.updateTable(importedFile[1], importedFile[3], "10.34", "11.40"); //String CodiceCliente, String indrizzo, String latitude, String longitute
}
}
when I try to access the elements for the linkedlist using
System.out.println("selected Customer : " + PublicDefinition.importList.get(0));
I got the output:
selected Customer : java.io.BufferedReader#420dc55b
I think this is the memory reference, but I want to retrieve the value of the linkedlist
my select function is:
public List<Customer> select(String codiceAzienda, String codiceCliente, String indrizzo) {
return jdbcTemplate.query(
"SELECT * FROM customers WHERE CodiceAzienda= ?",
new Object[] { codiceAzienda},
(rs, rowNum) -> new Customer(rs.getLong("id"),
rs.getString("CodiceAzienda"), rs.getString("Indrizzo"), rs.getString("codice_cliente"), rs.getString("Indrizzo")));
}
You added the toString() value of the importBuffer object, not the actual contents. The default toString() implementation (which every object inherits from... Object) returns ClassName#HashCode. So your output isn't wrong, but your input is.
See Object.toString() in the javadoc
Go ahead and perform:
PublicDefinition.importList.add(importBuffer.readLine());
Instead of :
PublicDefinition.importList.add(importBuffer.toString());
Since you are trying to output the contents of the buffered reader instead of the ClassName#Hashcode contents.
Replace
PublicDefinition.importList.add(importBuffer.toString());
with
PublicDefinition.importList.add(importedFile);
You are accidentally adding the string representation of BufferReader object, not the list of import files which sounds like your intention.

How do I make it so JOptionPane.showMessageDialog can sense multiple strings?

/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String grade = JOptionPane.showInputDialog(null, "Please Specify Your Grade");
String First_name = JOptionPane.showInputDialog(null, "What is your First Name?");
String Last_name = JOptionPane.showInputDialog(null, "What is your Last Name?");
]JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
}
How do I get the part where it says "Your Last Name is " + Last_Name to print the correct string? in my code it says that the string cannot be converted to an integer but the rest of that line works fine (using Netbeans IDE)
You are trying to pass multiple messages as separate parameters to the method JOptionPane.showMessageDialog, however the method only accepts a single message parameter. However, this parameter is not limited to just Strings; you can actually pass any Object as the message. See the JOptionPane javadocs for details on how JOptionPane handles various types of message parameters.
I think there are a couple approaches that could be used. One approach is to create a String that concatenates all of the results together. My suggestion would be to use a newline character (\n) to concatenate the results, so they appear one per line. Here is an example:
String message = "You are a " + grade + "\n"
+ "Your Name is " + First_name + "\n"
+ "Your Last Name is " + Last_name;
JOptionPane.showMessageDialog (null, message);
Another approach is to create an array out of the results, and pass the array as the message parameter:
String[] message = {
"You are a " + grade,
"Your Name is " + First_name,
"Your Last Name is " + Last_name
};
JOptionPane.showMessageDialog (null, message);
works also in the constructor :
JOptionPane.showMessageDialog(null, "You are a " + grade+ "\nYour Name is " + First_name+
"\nYour Last Name is " + Last_name);
and probably delete ] in your last line of code
JOptionPane has 3 showMessageDialog() methods, each with different arguments, let's look at each of them, but first we're going to use the following String:
String message = "You are a " + grade + " Your Name is " + First_name " Your Last Name is " + Last_name;
showMessageDialog(Component parentComponent, Object message) this method recieves the parentComponent (it shouldn't be null, instead pass the reference to your JFrame because otherwise you won't be blocking the parent component, so it won't be a modal Dialog) and the message, in your case it would be the String containing the name, last name, etc, you could use it this way:
JOptionPane.showMessageDialog(frame, message);
showMessageDialog(Component parentComponent, Object message, String title, int messageType) this method allows you to modify the icon (or the message type (A list of the full message types can be found on the docs) and the title of the dialog and you can use it as:
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) this allows you to use a custom icon and you can use it this way:
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
For more information you can check How to use Dialogs
Now, if you want to improve the format you can either use html tags as:
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
Or create your own custom JPanel where you add your components to it and then add that JPanel to the showMessageDialog on the Object message argument, but I'm leaving that part to you
This code will create the above output images, however you need to change the image path to your own path, the custom icon has been taken from here
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class DialogExamples {
private JFrame frame;
private ImageIcon icon = new ImageIcon("/home/jesus/Pictures/L5DGx.png");
public static void main (String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DialogExamples().createAndShowGui();
}
});
}
public DialogExamples() {
System.out.println(icon);
}
public void createAndShowGui() {
frame = new JFrame("Example");
String name = "Your name is Frakcool";
String grade = "Your grade is 5";
String lastname = "Your lastname is YajiSuzu";
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
// String message = name + " " + lastname + " " + grade;
JOptionPane.showMessageDialog(frame, message);
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
In your case you're getting the exception:
String cannot be converted to an int
because you're sending 4 parameters here:
JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
In this case, you're using the 2nd method I showed you above, so it's expecting to receive an int messageType on the 4th parameter, not a String.
This isn't something as a console.log() in JS, here you concatenate Strings with + operator, not with a , (comma).
NOTE:
As an aside note, your variable and method names should start with lowerCamelCase while your classes should start with UpperDromedaryCase as stated on the Java naming conventions
NOTE2:
You're not placing your program on the EDT which could cause you problems in the future, so be careful, my above code already solved that problem

Unwanted elements appearing when splitting a string with multiple separators in Java

I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
System.out.println("spart[4]: " + spart[4]);
But, I am getting some elements which are blank. The output is:
spart[0]: s
spart[1]: film
spart[2]:
spart[3]: fever
spart[4]: normal
My desired output is:
spart[0]: s
spart[1]: film
spart[2]: fever
spart[3]: normal
spart[4]: curse
Try with this:
public static void main(String[] args) {
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s]+");
for (String string : spart) {
System.out.println("'"+string+"'");
}
}
output:
's'
'film'
'fever'
'normal'
'curse'
I believe it is because you have a Greedy quantifier for space at the end there. I think you would have to use an escape sequence for the plus sign too.
String spart = s.replaceAll( "\\W", " " ).split(" +");

Categories