How can I separate strings line by line in Java? - java

Spring Street, 101/12
Postal Code: 8001
State: Washington
How can I separate line by line as in the example above?
address.setAddress(MessageFormat.format(
"{0} {1} Postal Code: {2}, State: {3}",restSmeApplication.getAddress(),restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "")
);

\n will work for you -
address.setAddress(MessageFormat.format(
"{0} \n {1} Postal Code: {2}, \n State: {3}",restSmeApplication.getAddress(),restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "")
);

This may help.
address.setAddress(String.format(
"%s %s \n Postal Code: %s,\n State: %s",
restSmeApplication.getAddress(),restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "")
);

MessageFormat is a heavy object.
For the intent of formatting the string one could use a static method String.format() which follows a printf() syntax and allows more options for formatting.
%n or \n can be used to make a new line.
String addressAsString =
String.format("%s %s%nPostal Code: %s,%nState: %s",
restSmeApplication.getAddress(),
restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",
restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "");
address.setAddress(addressAsString);
Keep in mind that line is not synonym to string. And the resulting sting is still one single string. We just insert some additional formatting into it so to make it's representation to be multi-line.

Related

OR condition in java substring method

While parsing the dynamic input string using the java substring method with start and end indexes, Can we use or condition in the end index of the substring method? Meaning end index could be either ')' or ',' for my use case.
Ex: my input string have below two formats
inputformat1 : Student(name: Joe, Batch ID: 23) is updated
inputformat2 : Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated
Now I am interested to get the "Batch ID" value every-time. I wanted to achieve this by substring method. Now I'm able to get the batch id value If I use any one of the indexes i.e, ')' or ','
String batchId= input.substring(input.indexOf("Batch ID: ")+9,input.indexOf(")"));
Can someone help me to the way to batch Id value basing on different end indexes?
You can use regex with replaceFirst to solve your problem for example ;
List<String> strings = Arrays.asList("Student(name: Joe, Batch ID: 23) is updated",
"Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated"
);
for (String string : strings) {
System.out.println(
string.replaceFirst(".*Batch ID:\\s+(\\d+).*", "$1")
);
}
Outputs
23
2503
If you want multiple groups you can also use Patterns like so :
Pattern pattern = Pattern.compile("name:\\s+(.*?),.*?Batch ID:\\s+(\\d+)");
Matcher matcher;
for (String string : strings) {
matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(
String.format("name : %s, age : %s", matcher.group(1), matcher.group(2))
);
}
}
Outputs
name : Joe, age : 23
name : John, age : 2503
You could use Math.min():
String batchId = input.substring(input.indexOf("Batch ID: ") + 9,
Math.min(tail_old.indexOf(")"), tail_old.indexOf(",")));

String.replaceAll(string,string) method gives unexpexted output

I have some amounts as input like:
Rs1 ,
INR10,954.00 ,
INR 45000 ,
INR 25000.70 ,
Rs.25000 ,
Rs.1,000 ,
Rs. 14000
these are the input formats I'm using
String getRuppee="Rs1"; // this string can not get the format and gives wrong output.
String val=getRuppee.toLowerCase()
.replaceAll(",", "")
.replaceAll("rs.", "")
.replaceAll("\"rs\"", "")
.replaceAll("rs", "")
.replaceAll("inr", "")
.replaceAll("inr ", "")
.replaceAll("mrp", "")
.replaceAll(" ", "");
This is how i get the output as per input show above, unless the first (Rs1).
Log.e("Converstion", "Converstion Balance."
+getRuppee.toLowerCase().
replaceAll("rs.", ""));
i need the output 1 but it gives me null.
Logcat Displays: "06-07 11:34:48.438: E/Converstion(8233): Converstion Balance."
Change your code as follows
String getRuppee="Rs1"; // this string can not get the format and gives wrong output.
String val=getRuppee.toLowerCase()
.replace(",", "")
.replace("rs.", "")
.replace("\"rs\"", "")
.replace("rs", "")
.replace("inr", "")
.replace("inr ", "")
.replace("mrp", "")
.replace(" ", "");
This is your problem here
.replaceAll("rs.", "")
As replaceAll is doing replacement based upon regexp, then this is replacing anything starting with rs followed by any char
Try using .replace instead which replaces all strings
Try below code:
String[] getRuppee = {"RS1", "INR10","954.00" , "INR 45000" , "INR 25000.70" , "Rs.25000" , "Rs.1,000" , "Rs. 14000"};
for (String tmp : getRuppee){
String val=tmp.toLowerCase()
.replaceAll(",", "")
.replaceAll("rs\\.", "") //check here
.replaceAll("\"rs\"", "")
.replaceAll("rs", "")
.replaceAll("inr", "")
.replaceAll("inr ", "")
.replaceAll("mrp", "")
.replaceAll(" ", "");
System.out.println(val);
}

Why is my string doesn't accept null?

I need the String receive the null value if it is not found in mapper.getChave is what is returned. What I do? If I only get nullPointerException
for(String chave : linha.keySet()) {
//Processa chave
String novaChave = mapper.getChave(chave.trim());
if (!(novaChave == null || novaChave.isEmpty())) {
//Processa valor
String novoValor = linha.getString(chave);
temp.append(novaChave, novoValor);
}
else {
extras.append(chave, linha.getString(chave));
}
}
Log
java.lang.NullPointerException
at oknok.validacao.readers.PlanilhaReader.processaAtributosPlanilha(PlanilhaReader.java:237)
Line 237 is
String novaChave = mapper.getChave(chave.trim());
**UPDATE: The first time the loop runs, i have a Nullpointer and chave contains a value
System.out.println(chave.isEmpty() + "\t" + chave + "\t" + chave.trim());
Output
false Veículo Veículo
You need to add null check for mapper as well as chave.
if (mapper!= null && chave != null && !"".equals(chave) {
// do something
}
mapper.getChave(chave.trim())
^ ^ possible places for NPE.
Most probably value of chave or mapper would be null and you are calling trim() and .getChave() on them respectively causing nullpointer
You need to check whether chave is null before trimming it or doing anything else (I'm assuming that mapper is pre-initialised and not null, but you should check that too)
e.g.
if (chave != null && !"".equals(chave.trim()) {
// now do something
}
You may find it easier (more intuitive) to use something like Apache Commons StringUtils.isNotBlank(String). See here for the doc.
There is a null string reference in linha.keySet().
Follow code change null string to "" : you can change "" to anything you like
String novaChave = mapper.getChave((chave == null ? "" : chave).trim());

How to make a local variable accessible outside the loop in java

I have a txt file in while one line is like this :
"Execution Status: Pass"
I want to take the value out : pass from here.
I am using below code :
String patternString1 = "(Execution) (Status:) (.*)";
Pattern patt1 = Pattern.compile( patternString1 );
BufferedReader r = new BufferedReader(new FileReader( "c:\\abc.txt" ));
String line;
while ( (line = r.readLine()) != null ) {
String g11 = null;
Matcher m1 = patt1.matcher( line );
while ( m1.find() ) {
g11=m1.group(3);
System.out.println(g11+"HI1"); //Line1
}
System.out.println(g11+"HI1"); //Line2
}
While Line 1 is giving the desired output as "pass" I am not getting this expected output from Line 2.
Could any one of you please help me in accessing the local variable out of the loop?
Declare String g11 as a local variable at the start of your method
String g11=""; -- declare g11 as a local variable
String patternString1 = "(Execution) (Status:) (.*)";
Pattern patt1 = Pattern.compile(patternString1);
Add the rest of your code here.........
Could you try changing following line:
while (m1.find())
to
if(m1.find())
It should give the result you want
How about the easy way:
String result = line.replaceAll(".*: ", "");
This line says "replace everything up to and including colon space with nothing" (ie delete it).
If there is only one instance of this match in single line then use if instead of while (m1.find()) loop or break the loop once match is found.
Sample code:
while ( (line = r.readLine()) != null ) {
String g11 = null;
Matcher m1 = patt1.matcher( line );
if( m1.find() ) {
g11=m1.group(3);
}
if(g11 != null){
System.out.println(g11+"HI1"); //Line2
}
}

printing statement with operator ? : causes unexpected output

I had to create an output depending on an boolean state like
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", " + smily == null ? ":)" : ":("); //$NON-NLS-1$
System.out.println(buff.toString());
The problem is the String creation statement
", " + smily == null ? ":)" : ":("
I tested it in 2 different eclipse environments (and may be also 2 diofferent java version, this i did not checked) and the result was different.
Result 1:
:(
Result 2:
false:(
Of course, if i added brackets it is working
buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$
Expected Result:
, :)
Can please somebody explain to me, why java interprets the statement that way?
Thanks
If you check the operator precedence (see this tutorial), then you will notice that addition (+) comes before equality (==). In other words, Java will first evaluate ", " + smily => ", null" before evaluating equality, therefor ", " + smily == null evaluates to false, and so the ternary operator evaluates to ":(".
BTW: You could have avoided this by not concatenating strings before adding them to the StringBuffer (the whole point of a StringBuffer is to make concatenation cheaper):
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", ");
buff.append(smily == null ? ":)" : ":(");
the expression ", " + smily == null ? ":)" : ":(" is evaluated as (", " + smily) == null ? ":)" : ":("
This explains your result 1. To be honest, I don't know why result 2 was possible.
StringBuffer.append() takes a String parameter. So when you put this without brackets
buff.append(", " + smily == null ? ":)" : ":(")
at the time of evaluation will be ", " + null. So when the evaluation happens it is always false.
As for why the same code returned two results I can only assume that two different Java versions were used and they handled this situation differently.
String smily = null;
StringBuffer buff = new StringBuffer();
if(smily == null){
buff.append(", " + ":)") ; //$NON-NLS-1$
}else{
buff.append(", " + ":(") ; //$NON-NLS-1$
}
Try this.....................
buff.append(", " + smily == null ? ":)" : ":(");
- In the above statement you are Not mentioning the smily == null ? ":)" : ":(" to be evaluated in the proper way it has to be.
- To solve this you have to use BODMAS rule, the below are always evaluated in the way it has been listed from Left to Right.
Bracket
Power
Division and Multiplication
Addition and Substraction
- Use Bracket to enclose the smily == null ? ":)" : ":("
Eg:
public class Test {
public static void main(String[] args){
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$
System.out.println(buff.toString());
}
}
Output: , :)

Categories