StringBuilder cannot append new line - groovy

So whenever I try to append a new line using a StringBuilder, I can't get a new line whatsoever, I tried:
errorMessage.append(System.getProperty("line.separator"));
errorMessage.append(System.getProperty("\n"));
errorMessage.append(System.getProperty("\r\n"));
errorMessage.append(System.getProperty("line.separator"));
basically everything within the first 3 pages of google results, it's so frustrating. I am implementing it in a for loop like this : idk if it helps, but any suggestions are appreciated.
public String getIDs(HashMap<String,List<Integer>> errorMap ){
StringBuilder errorMessage = new StringBuilder();
for (String state:errorMap.keySet()){
List<Integer> listofId = errorMap.get(state);
if (listofId){
StringBuilder listOfIds = new StringBuilder();
for (Integer id :listofId) {
listOfIds.append(id.toString()+' , ')
}
errorMessage.append(state +" Trades: " +listOfIds.toString())
errorMessage.append("\n")
}
}
return errorMessage.toString();
}

Use
errorMessage.append("\n");
Instead of
errorMessage.append(System.getProperty("\n"));

You should directly be using builder.append("\n"). \n is not a property.
Also append method returns builder object itself (Builder pattern). So you can easily do builder.append("\n").append("text1").append("\n").append("text2").....

Related

How would I get a single string from the result of a razor foreach loop? (preferably not Linq)

(hope everyone's well).
Please could I get some advice on how best to get a single string as a variable from the following foreach loop with razor (preferably not Linq)...
#if (selection.Any())
{
foreach(var item in selection){
foreach (var searchLocationItem in item.searchLocation)
{
if (!String.IsNullOrEmpty(searchLocationItem)){
counter++;
#searchLocationItem<text>,</text>;
}
}
}
}
The above code outputs a string exactly as I require, but as html, not a reusable variable.
Any help on how to get the result efficiently as a single string variable would be appreciated.
Regards,
You can use a stringbuilder:
StringBuilder builder = new StringBuilder();
foreach(var item in selection){
foreach (var searchLocationItem in item.searchLocation)
{
if (!String.IsNullOrEmpty(searchLocationItem)){
counter++;
builder.Append(String.Format("{0}<text>,</text>;", searchLocationItem));
}
}
}
#builder.ToString()

BufferedReader is sometimes empty

I have Loader class where I load txt file into BufferedReader from resources and return this field. I use this method but it acts really strange(for me). When I don't put
String str = bufferReader.readLine(); after
bufferReader = new BufferedReader(fileReader);
(in Loader class) than bufferReader in another class is empty, and readLine() returns null. When I write that piece of code in Loader class, I can read each line from txt, except the 1. one which is read in Loader class. Also, I can't read last line if I dont put enter at the end.
public BufferedReader loadFromFileToBufferReader(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
System.out.print(getClass().getClassLoader().getResource("resources/" + fileName));
File file = new File(classLoader.getResource("resources/" + fileName).getFile());
BufferedReader bufferReader = null;
try (FileReader fileReader = new FileReader(file)) {
bufferReader = new BufferedReader(fileReader);
String str = bufferReader.readLine();
} catch (IOException e) {
System.err.println("Something went terribly wrong with file reading");
}
return bufferReader;
}
and usage:
public Database() {
productsInDatabse = new ArrayList<>();
codesList = new ArrayList<>();
loader = new LoadFromFile();
BufferedReader output = loader.loadFromFileToBufferReader("database.txt");
Product product;
String line;
String[] array;
try {
line = output.readLine();
while (line != null) {
You should paste your code here because it's hard to deduce all the possible causes of this without seeing the code on 100% but I am guessing you have it the same file open at the same time from multiple sources without closing it before from one? Could be literally millions of little things, just telling you how the same error happened to me.

Spell checker in android

I want to create an application in which it checks if the word typed by user is correct or not using Google Dictionary ?
i have used the below link . But the problem with the given example is that it suggests the different words. I don't want suggestion, instead i want to only check that word entered is correct or not.
I haven't worked on it yet. But you can probably modify it as:
When you get the suggestions, instead of appending them to StringBuilder, and showing that StringBuilder to MainView, just compare all suggestions with your input string of edittext.
If it matches, then the spell is correct, else the spell is incorrect.
Code snippet:
#Override
public void onGetSuggestions(final SuggestionsInfo[] arg0) {
isSpellCorrect = false;
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < arg0.length; ++i) {
// Returned suggestions are contained in SuggestionsInfo
final int len = arg0[i].getSuggestionsCount();
if(editText1.getText().toString().equalsIgnoreCase(arg0[i].getSuggestionAt(j))
{
isSpellCorrect = true;
break;
}
}
}
Hope this helps.

How to convert from ArrayList to String?

After compiling an ArrayList in java, how do I print it as a string?
Using ArrayList.toString() gives the values with brackets around them and commas between them.
I want to print them without brackets and only spaces between them.
(Assuming Java)
You can write your own method to do that:
public static <T> String listToString(List<T> list) {
StringBuilder sb = new StringBuilder();
boolean b = false;
for (T o : list) {
if (b)
sb.append(' ');
sb.append(o);
b = true;
}
return sb.toString();
}
Or, if you're using Guava, you can use Joiner:
Joiner.on(' ').join(list)
Similarly, if you just are interested in printing, you can avoid creating a new string all together:
public static <T> void printList(List<T> list) {
for (T o : list) {
System.out.print(o);
System.out.print(' ');
}
System.out.println();
}
If you're using Eclipse Collections, you can use the makeString() method.
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
Assert.assertEquals(
"one two three",
ArrayListAdapter.adapt(list).makeString(" "));
If you can convert your ArrayList to a FastList, you can get rid of the adapter.
Assert.assertEquals(
"one two three",
FastList.newListWith("one", "two", "three").makeString(" "));
Note: I am a committer for Eclipse collections.
for c#
string.Join(" ", _list);
Not sure what language you're using, but try either:
ArrayList.join()
or
ArrayList.toArray().join()
for(int i = 0; i < arraylist.size(); i++){
System.out.print(arraylist.get(i).toString + " ");
}
???

Lines of a StreamReader to an array of string

I want to get a string[] assigned with a StreamReader. Like:
try{
StreamReader sr = new StreamReader("a.txt");
do{
str[i] = sr.ReadLine();
i++;
}while(i < 78);
}
catch (Exception ex){
MessageBox.Show(ex.ToString());
}
I can do it but can't use the string[]. I want to do this:
MessageBox.Show(str[4]);
If you need further information feel free to ask, I will update.
thanks in advance...
If you really want a string array, I would approach this slightly differently. Assuming you have no idea how many lines are going to be in your file (I'm ignoring your hard-coded value of 78 lines), you can't create a string[] of the correct size up front.
Instead, you could start with a collection of strings:
var list = new List<string>();
Change your loop to:
using (var sr = new StreamReader("a.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
list.Add(line);
}
}
And then ask for a string array from your list:
string[] result = list.ToArray();
Update
Inspired by Cuong's answer, you can definitely shorten this up. I had forgotten about this gem on the File class:
string[] result = File.ReadAllLines("a.txt");
What File.ReadAllLines does under the hood is actually identical to the code I provided above, except Microsoft uses an ArrayList instead of a List<string>, and at the end they return a string[] array via return (string[]) list.ToArray(typeof(string));.

Resources