refactoring Java to get string length - java

I am starting out with Java and trying to find a neat way of refactoring the below code so that I can set the firstName variable as a string and in the same line get and set the firstNameLength string length as an integer.
String firstName = "Boris";
int firstNameLength = firstName.length();
I have been trying variations of the below code but to no avail!
int newAge = String firstName = "Boris".length();

You can't declare 2 new variables, but assignment of firstName is possible.
String firstName;
int newAge = (firstName = "Boris").length();
(You could put both in the same line).
I doubt however, that anyone would consider this more readable than
String firstName = "Boris";
int newAge = firstName.length();
and there are no other benefits.

There's no way you can delcare two variables of different type in one statement.
So you're stuck with 2 statements anyway. So you could put it in one line like this:
String name; int length = (name= "Boris").length();
But really, what's the point?
I guess if you want to make your code more streamlined, you should think about why you need an extra variable holding the length in the first place - as this can always be computed later. So you keep redundant information.

Actually another solution would be to use StringUtils in the following way:
int length = StringUtils.length("Boris");
But this comes with the Apache Common package.

Related

java I thought strings were immutable

I was always told strings in java are immutable, unless your going to use the string builder class or string writter class.
Take a look at this practice question I found online,
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
stringTimes("Hi", 2) → "HiHi"
stringTimes("Hi", 3) → "HiHiHi"
stringTimes("Hi", 1) → "Hi"
and the solution came out to be
Solution:
public String stringTimes(String str, int n) {
String result = "";
for (int i=0; i<n; i++) {
result = result + str; // could use += here
}
return result;
}
As you see in the solution our 3rd line assigns the string , then we change it in our for loop. This makes no sense to me! (I answered the question in another nooby way ) Once I saw this solution I knew I had to ask you guys.
Thoughts? I know im not that great at programming but I haven't seen this type of example here before, so I thought I'd share.
The trick to understanding what's going on is the line below:
result = result + str;
or its equivalent
result += str;
Java compiler performs a trick on this syntax - behind the scene, it generates the following code:
result = result.concat(str);
Variable result participates in this expression twice - once as the original string on which concat method is called, and once as the target of an assignment. The assignment does not mutate the original string, it replaces the entire String object with a new immutable one provided by concat.
Perhaps it would be easier to see if we introduce an additional String variable into the code:
String temp = result.concat(str);
result = temp;
Once the first line has executed, you have two String objects - temp, which is "HiHi", and result, which is still "Hi". When the second line is executed, result gets replaced with temp, acquiring a new value of "HiHi".
If you use Eclipse, you could make a breakpoint and run it step by step. You will find the id (find it in "Variables" View) of "result" changed every time after java did
result = result + str;
On the other hand, if you use StringBuffer like
StringBuffer result = new StringBuffer("");
for(int i = 0; i < n; i++){
result.append(str);
}
the id of result will not change.
String objects are indeed immutable. result is not a String, it is a reference to a String object. In each iteration, a new String object is created and assigned to the same reference. The old object with no reference is eventually destroyed by a garbage collector. For a simple example like this, it is a possible solution. However, creating a new String object in each iteration in a real-world application is not a smart idea.

How to pad a string with blanks if desired length isn't long enough?

I am creating a random access file that stores a player's name, rank, and skill, and I'm making it so that if you type in a player's name that is longer than 26, it's cut out at 26, and if it is shorter than 26, I want to pad it with blanks.
I figured out the subString to make sure only the first 26 get chosen, but I was wondering what you guys would suggest to make sure I have 26 padded blanks if I didn't put any value. This is only a snippet of my code, if you would like me to add more, I will.
public static String PlayerNameMethod (RandomAccessFile store){
try{
String PlayerName = input.next();
store.writeUTF(PlayerName);
if (PlayerName.length()> 26){
PlayerName.substring(0,26);
System.out.print("The Player Name is" + PlayerName);
}
if (PlayerName.length()< 26){
//PART I CANT FIGURE OUT
}
There are many ways in which you can do that - the most straightforward one being a loop in which you add spaces until the string is long enough.
But one way which has very short code and uses built in functions is the String.format function:
PlayerName = String.format("%-26s", PlayerName);
Note that you have some problems in the rest of your code. The line:
PlayerName.substring(0,26);
doesn't do anything. Strings are immutable, meaning that functions that change a string always return the new string - they don't modify the original one.
So that line should be:
PlayerName = PlayerName.substring(0,26);
The answer that #Erwin has mentioned is the most concise.
However if you want to do it yourself this is what you would need to do.
if (PlayerName.length() < 26)
{
StringBuilder paddedName = new StringBuilder(PlayerName);
for (int i = 0; i < 26 - PlayerName.length(); i++)
{
paddedName.append(" ");
}
PlayerName = paddedName.toString();
}
Note: java convention dictates that you should have variable names starting with a lower case. In your case playerName
Create a string of length=26-PlayerName.length() with each character as blank and append it to the PlayerName

Strings for Calculator

I want to write a calculator that takes the numbers from text fields and adds them together to give them out in a text area.
It works as far as taking the two numbers from the text fields, but when I add them together it will give out: 1+1=11.
How can I add the two strings so it will equal 2?
This is my source code:
private void ButtonPlusActionPerformed(java.awt.event.ActionEvent evt) {
String Nummer1 = Zahl1.getText();
String Nummer2 = Zahl2.getText();
int intZahl1 = Integer.parseInt(Nummer1);
Integer integerZahl1 = new Integer(Nummer1);
int intZahl2 = Integer.parseInt(Nummer2);
Integer integerZahl2 = new Integer(Nummer2);
Result.setText(Nummer1 + Nummer2);
Result is the name of my text area and the divers Nummers are just variables, as you may have noticed already.
You're adding the Strings not the ints. You will want to add integerZahl1 and intZahl2 instead of Nummer1 and Nummer2.
For example,
int intResult = intZahl1 + intZahl2;
Result.setText(String.valueOf(intResult));
Also as an aside, you'll want to learn and follow Java naming conventions. Variable and method names should start with a lower-case letter, and class names should start with an upper-case letter.
Dom states:
Or you could just do Result.setText(intZahl1 + intZahl2); if you only need to display the result.
Dom, please understand that setText(...) requires a String parameter, not an int, so your method call will not be allowed by the compiler. If one tries the trick of
Result.setText("" + intZahl + intZahl2);
they'd get 11 again. For your technique to work, you'd need to do something like,
Result.setText(String.valueOf(intZahl1 + intZahl2));
Edit
Also you will want to use ints and not Integers.

Java String(Query String) manipulation

I have a strange scenario. Query string has value first=second=12123423423423432323234
String queryString = request.getParameter("first=second=12123423423423432323234")
So i have to:
capture 'first' and 'second' values
validate the query string has 'first' and 'second'.
Could someone please share how I can achieve this in the best possible way?
I really appreciate your help on this.
I believe your query string should look like
first=firstvalue&second=secondvalue
You can use this in your servlet to print the query string
String firstValue = request.getParameter("first");
String secondValue = request.getParameter("second");
System.out.println("Query String:first="+firstValue+"second=+"secondValue);
In your case, where the query string is
first=second=12123423423423432323234
You could do this
String first = request.getParameter("first");
String second = request.getParameter("second");
if(first.contains("second=")){
second = first.split("second=")[1];
first = first.split("second=")[0];
}
out.println("[First:"+first+"][Second:"+second+"]");
If your parameters are separated properly by & (i.e. first=&second=something), then simply .getParameter("first") and .getParameter("second")
Otherwise, you'd need to play with the string - probably split around =, and for the value of first cut until second is encountered. Though I fail to see how will that work if first has a value: first=foosecond=bar?

incompatible types error String[]

I get this error message when i try to run my program
error: incompatible types
epost = split[3];
^
required: String[]
found: String
here is my code:
String [] split = ordre.split(" ");
String [] epostadr;
while(split >= 3) {
String [] epostadr = split[3];
}
I want to save the epostadr in split[3] but it wont let me do that because split only saves Strings while epostadr is a String [], what can i do to change this?
Any help would be greatly appreciated.
String [] epostadr = split[3];
split[3] is of type String while epostadr is of type String[]
Maybe you want to declare epostadr as String? [not sure I am following what you are trying to achieve]
First off, you don't have an array:
String [] epostadr;
This declares a variable than can have an array reference assigned to it.
Then you have:
String [] epostadr = split[3];
This makes no sense. split[3] is a String; you can't assign that to a variable declared as a String array.
If you need epostadr to be an array, you need to create one, assign it, then put the String in a specific location:
String [] epostadr = new String[maxNumberOfStrings];
...
epostadr[index] = split[3];
Edit: this is ignoring that the rest of your code doesn't actually do what you think it does. Your while loop (if it were written correctly) will loop forever; split.length is never going to change. Given these issues you may well want to invest in a beginner's guide to Java/programming, or at the very least go through the Java tutorials available on Oracle's website.
When you use split on a String, it makes it into a String[] so you got that right when making split as a String[]. However, in each array slot, there is a String. You are basically trying to making epostadr, which you declared as a String[], a String and that's where the incompatible types come from. A String[] can't be a String.
It's hard to know exactly what you're trying to do from this code so I'll go through and let you know what's happeneing. It looks like you're trying to take a string stored in the variable ordre, and split it so that each word has it's own index in a string array called split.
So if ordre contained the string "My name is Jones."
String [] split = ordre.split(" ");
That line would create an array named split containing the following values {My, name, is, Jones}
Here is the part that maybe you can clarify, it looks like you want those values to be in the string array epostadr, or maybe just the 3rd index which in this case would be "Jones" since indexes start with 0.
Putting the values in epostadr would be redundant since split already contains those values. But if you really wanted to copy it you could do this.
String [] epostadre = split;
If you wanted just the 3rd index, epostadre can't be a string array, but must be declared as a string and you would do this...
String epostadre = split[3];
Here you're declaring a String, which will hold one value, and setting it equal to the string that is contained in the 3rd index of split, which is Jones. split[0] = "My" split[1] = "name" and so on.
I hope that helps, let me know if you need more clarification.

Categories