User Class Information - java

How would you put your first name and last name together with a period(.) in the middle and assign it to a String of FullName.
FullName = +FirstName '.'+ LastName;
It has got a big red 'X' next to the line. The error is
The method FirstName() is undefined for the type Username
The method LastName() is undefined for the type Username
The operator + is undefined for the argument type(s) String
Syntax error on token ""."", delete this token.
Any suggestions?

You're on the right lines, but your syntax is a little off.
String fullName = firstName + "." + lastName;
NOTE: I've used the proper naming conventions, which can be found here.
This works because you declare a new String, fullName. You then assign it the value of firstName, then a ".", then the value of lastName. This code assumes that firstName and lastName has already been declared previously.
If you wanted to be more efficient..
Then you can use a class called a StringBuilder. This is because concatenating String objects in Java is considered bad practise and highly inefficient, and StringBuilder offers a nicer solution to it. Sample code would be as follows.
StringBuilder builder = new StringBuilder();
builder.append(firstName);
builder.append(".");
builder.append(lastName);
String fullName = builder.toString();
Edit: Here's a link to the working code: http://ideone.com/KIIOgo

Related

Convert strings in an array to Title Case - JAVA

I have an array of objects (customer) that has components: first_Name & last_Name. I am trying to convert both the first name and last name of each customer to title case. I have tried making several different methods that will convert strings to title case, but all of them have failed. This is the last thing I have tried and I cannot figure out why it would not capitalize the first letter of the first name and the first letter of the last name.
for (Customer c : customers){
c.setFirst_name(c.getFirst_name().charAt(0).toUpperCase());
}
I have checked that the first name and last name indeed contain an only-letter string with a lower case letter as the first letter in each. The error intellisense is giving me is that "char cannot be dereferenced"
This method capitalizes the 1st char of the string and makes the rest lower case:
public static String toTitle(String s) {
return (s.length() > 0) ? s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase() : "";
}
so use it:
for (Customer c : customers){
c.setFirst_name(toTitle(c.getFirst_name()));
c.setLast_name(toTitle(c.getLast_name()));
}
String.charAt() returns a char, which is a primitive type and therefore does not have methods. So the toUpperCase() call is not allowed there.
What you probably want is to create a Character object there, maybe a String. We don't know because you never showed the setFirst_name() signature.
String values is immutable. You try to change the first cahracter. That does not work. You must make a new string: Extract the first character of the original string, convert it to upper case and append the rest of the original string.

How to format and replace groups using RegEx (or Maybe not?) (Java)

output = output.replaceAll("%(\\w+)%",getVar("$1"));
public String getVar(name){...return formatted;}
I have this line of code (In JAVA), and a function called getVar() that will give me the value of the variable with the name we want. The function is working perfectly, but this code doesn't seem to look for the groups anymore.
The String I am formatting with this regex is:
"My name is %name% and I am %age% years old."
And instead of giving me back: "My name is Paulo and I am 15 years old." (Because name = Paulo and age = 15) It gives me nothing back. Instead of replacing the regex with getVar(name) or getVar(age), it replaces it with getVar("$1").
Is there some way of fixing it, is this a bug, or intended behaviour? And if it is, how can I get the same result another way?
EDIT:
for(String i: varnames){
output = output.replaceAll("%"+i+"%",getVar(i));
}
Does the job for this specific case... But yet, is there a way to use functions inside of replaceAll() and maintaining the groups (e.g. $1, $2) working inside the function?
EDIT 2:
//Variables//
ArrayList<String> varnames = new ArrayList<String>(0);
ArrayList<String> varvalues = new ArrayList<String>(0);
//end of Variables
private String getVar(String name){
String returnv = "";
if(varnames.contains(name.toLowerCase())) returnv = varvalues.get(varnames.indexOf(name.toLowerCase()));
//System.out.println("\n\n"+name+"\n\n");
return returnv;
}
private String format(String input){
String output = input;
output = output.replace("[br]","/n");
for(String i: varnames){
output = output.replaceAll("%"+i+"%",getVar(i));//This is how I am parsing the variables.
}
//Here I want to handle inline functions... for example: a function called 'invert' that would switch the letters. If the input String that is being formatted (output) contains the regex, the function needs to evaluate and replace.
//How I tried to do it:
output.replaceAll("invert\((\w+)\)",invertLetters("$1"));
return output;
}
public String invertLetters(String input){//Inverts the letters of the String}
As mentioned by codisfy it is not clear at all if you are talking about java or javascript, as you use the replaceAll method I will consider that you use java. However what I will explain hereunder is valid for most (if not all) regex engines independently about the programming language.
When you call outputString=inputString.replaceAll("REGEX","REPLACEMENT"); the method replaceAll will configure its internal regex engine, build a finite automaton (for simplicity let's omit the difference between DFA/NFA here) with the regex passed as parameter and analyse the inputString on which it is called in order to do the replacement and return the result (outputString).
When the method is called it also needs a replacement String (REPLACEMENT) that is a normal string which may contain or not back-references to some groups, in order to enable some contextual replacement (using the syntax $1, $2 or \1, \2,... depending on the language).
What is very important to understand is that the regex as well as its replacement string are both just simple strings with no special meaning outside the regex engine (the method replaceAll).
Therefore, if you reuse them in other methods (for example by passing them as parameters) they will be interpreted literally as it is the case with other normal strings.
So do not expect that $1 is replaced by name or age in your call getVar("$1"). It will be just $1 and nothing else.
Also, this being said, your method public void getVar(name){...} does not even return a string since its return type is void, as consequence, if you code in java and if you use replaceAll method of String class (which expects 2 strings as arguments) it will NOT even compile in the first place.
I will let you implement the rest of the code but if you change your replacement loop in the following way it should work:
String input="My name is %name% and I am %age% years old.";
Matcher matcher = Pattern.compile("%(\\w+)%").matcher(input);
String output=new String(input);
while (matcher.find()) {
System.out.println("------------------------------------");
System.out.println("Back reference:" + matcher.group(1));
String group=matcher.group(1);//give access to the first matching group so that it can be reused
output=output.replaceAll("%"+group+"%", getVar(group));
}
System.out.println(output);
getVar method code: (I will let you adapt it)
public static String getVar(String name){
if(name.equals("name"))
return "Paulo";
return "15";
}
OUTPUT:
------------------------------------
Back reference:name
------------------------------------
Back reference:age
My name is Paulo and I am 15 years old.

How can I ignore spaces in a substring?

I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in Chicago,IL, everything works, but if they type in Chicago, IL, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
I have also tried this:
String state = location.substring(location.indexOf(",".trim()) + 1);
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
How can I fix this, so that even if a user puts in 2 or 4 spaces after
the comma it still shows the same results as the first case?
you can use location.replaceAll(" ", "")
for extracting the location into city,state
you can use split() method as
String location[]=location.split(",");
Now
String city=location[0];
String state=location[1];
EDIT:(for Whome)
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
you were in the right direction by using trim(). However, you put it in the wrong place.
",".trim() will always yield ",". you want to trim the result of the substring operation:
String state = location.substring(location.indexOf(",") + 1).trim();
Trim the entire result. For example:
String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();
try using java.lang.String trim() function in the correct place.
trim on ",".trim() will produce ",".
Need to trim() the final result.
if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}
Use
String state = location.substring(location.indexOf(",") + 1).trim();
Instead of
String state = location.substring(location.indexOf(",".trim()) + 1);
That should work.

Append String directly or use StringBuilder [duplicate]

This question already has answers here:
When is `StringBuilder` is preferred instead appending `String` to `String`? [duplicate]
(2 answers)
Closed 7 years ago.
Say I have 3 String variables:
String firstName = "aaa";
String middleName = "bbb";
String lastName = "cccc";
To append string variables we can use:
String fullName = firstName + "-" + middleName + "-" +lastName ;
Or we can use StringBuilder:
StringBuilder builder = new StringBuilder();
builder.append(firstName);
builder.append("-");
builder.append(middleName);
builder.append("-");
builder.append(lastName);
String fullName = builder.toString();
When to use StringBulider or when to append it directly?
As a programmer we should always care about the readability of our code and the first case looks quite readable to me than the second one.
Now if your question is which one should I choose ?
Than answer is any of them and you should not bother for this.StringBuilder only make difference with loop, other than that currently both of the cases would be almost same.
Simplest way : If you have access to apache common, you could use StringUtils.join().
Next, if all the Strings could be marked as final, then use + directly as using + on final Strings (which are compile time constants) is actually a compile-time operation.
If, you don't want to do the 2 things above, then use StringBuilder to concatenate strings (Even though + on Strings is done using StringBuilder internally.

How to access to the text inside a Swing JPasswordField object?

In a JFrame class I have a JPasswordField object, something like this:
pswdTextField = new JPasswordField(20);
externalPanel.add(pswdTextField, "w 90%, wrap");
I try to access to its inserted content (the password inserted by a user) by the following lines of code:
char[] pswd = pswdTextField.getPassword();
System.out.println("Password: " + pswd.toString());
The problem is that when I go to print this content I obtain the following output: Password: [C#d5c0f9 and not the inserted password
Why? What is it means? How can I obtain the inserted password?
Tnx
Andrea
Why? What is it means?
If you go through docs than you got this reasons.
For stronger security, it is recommended that the returned character
array be cleared after use by setting each character to zero.
How can I obtain the inserted password?
You can get password by,
char[] pswd = pswdTextField.getPassword();
String password=new String(pswd);
Or, you can directly print on System.out.print
System.out.print(pswd); // It override ...print(char[]) method
// without concat with another String.
Edit
Please note that, If you concat char[] with String than it will inherit Object.toString() method.
System.out.print("Password: " +pswd);// It will print like Password: [C#d5c0f9
pswdTextField.getText() is what you were looking for. toString() will not return the text inside a JPasswordField().
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of: getClass().getName() + '#' +
Integer.toHexString(hashCode())
so use
System.out.println("Password: " +pswdTextField.getText());
getText() is depreciated for JPasswordField
in Java source, its written above getText() definition
" For security reasons, this method is deprecated. "
so getPassword() is preferred.
The problem you are facing is that you are printing an array using System.out.println()
either create a string using that character array
or use for loop to access each element one by one
for(int i=0;i < charArray.length;i++)
System.out.print (charArray[i]);

Categories

Resources