This is probably a simple enough solution. I am use a StringBuffer to create a String from all the elements of a Set (WardenSet). But I don't want a comma at the end of the last element. here is my code
sb = new StringBuffer();
for (String s : WardenSet) {
sb.append(s + ", ");
}
System.out.println(wardenInitials = sb.toString());
CURRENT OUTPUT: MD, BH,
WANTED OUTPUT: MD, BH
You will have to use an explicit iterator.
sb = new StringBuffer();
Iterator it = WardenSet.iterator();
while (it.hasNext()) {
String s = (String) it.next();
sb.append(s);
if (it.hasNext()) {
sb.append(", ");
}
}
System.out.println(wardenInitials = sb.toString());
Also, it's a good idea to replace StringBuffer with StringBuilder unless you're going to have multiple threads using it.
If you're using Java 8, you can use StringJoiner:
System.out.println(new StringJoiner(", ").join(WardenSet).toString());
If you're using Guava, you can use Joiner:
System.out.println(Joiner.on(", ").join(WardenSet).toString());
Related
Here's my code:
Crashes.TrackError(ex,
new Dictionary<string, string> {
{"RunQuery", "Exception"},
{"sql", s },
{"Device Model", DeviceInfo.Model },
{"Exception", ex.ToString()}
});
Everything works but I find that Appcenter limits the length of the parameters to 125 characters so it's useless for me as I can never see all of the sql or the ex string.
Has anyone found a way to get around this?
I ran into the same problem. My solution was to break my string into groups of 125 character strings and iterate through while logging. I chatted with AppCenter support. They have no way of extending this length currently.
Here is a scrubbed version of my code:
var tokenChunks = LoggingHelper.SplitBy(extremelyLongString, 120);
string title = "Long string here";
var props = new Dictionary<string, string>();
int item = 0;
foreach(string chunk in tokenChunks)
{
string chunkIndex = string.Format("item: {0}", item++);
props.Add(chunkIndex, chunk);
}
Analytics.TrackEvent(title, props);
Where the LoggingHelper class is:
public static class LoggingHelper
{
public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) throw new ArgumentException();
if (chunkLength < 1) throw new ArgumentException();
for (int i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
yield return str.Substring(i, chunkLength);
}
}
}
I should give credit to this post https://stackoverflow.com/a/8944374/117995 by #oleksii for the SplitBy method.
I am trying to use an ArrayList of string values from one table, modify the strings based on whether or not the string ends with ".tif" or ".tiff", then transfer the resulting strings to a new table. However, when I invoke this method, the new table only receives the first modified string. I'm not sure what is wrong with my logic, the first element of the original table would be checked to see if it satisfies a condition (either ending in ".tif" or ".tiff") then from there that string would be modified, added to the ArrayList fData, then iterate to the next table value. I don't understand why the method doesn't return more than one element contained within fData?
public ArrayList<String> getTableData() {
StringBuilder str = new StringBuilder();
String fString = null;
ArrayList<String> fData = new ArrayList<String>();
while(filePaths != null) {
int size = filePaths.size();
for (int i = 0; i <= size; i++) {
String pathName = filePaths.get(i);
if (pathName.endsWith(".tif")) {
int pathLength = pathName.length();
str = new StringBuilder(filePaths.get(i));
str.insert(pathLength - 4, "_Data");
fString = str.toString();
fData.add(fString);
tableModel2.addRow(new String[] { fString });
return fData;
}
else if (pathName.endsWith(".tiff")) {
int pathLength = pathName.length();
str = new StringBuilder(filePaths.get(i));
str.insert(pathLength - 5, "_Data");
fString = str.toString();
fData.add(fString);
tableModel2.addRow(new String[] { fString });
return fData;
}
}
tableModel2.fireTableDataChanged();
}
return null;
}
`
It appears that you are returning from getTableData() as soon as you do a single replacement. Instead, you should return only after having iterated over every file path.
Remove the return statements inside the loops and instead replace return null at the end with return fData.
Please pardon me for my weak porgramming ability. I'm trying to write a method converting english to morse code. As you can see, I use hashmap to store the equivalant and then convert it and stored the morse code into the variable 'result'. My concern is I can't return the variable 'result' outside of the loop. If i return 'dataInput', isn't it just returning the original input? How can I return the correct result?
public static String morseCode(String dataInput)
{
Map<String, String> morseCode = new HashMap<String, String>();
morseCode.put("a", ".-");
morseCode.put("b", "-...");
morseCode.put("c", "-.-.");
for (int i = 0; i<dataInput.length(); i++)
{
String result = (String)morseCode.get(dataInput.charAt(i)+"");
//convert input data into morse code
}
return dataInput;
}
Try like this:
import java.lang.StringBuffer; //at the top
Map morseCode = new HashMap();
morseCode.put("a", ".-");
morseCode.put("b", "-...");
morseCode.put("c", "-.-.");
StringBuffer buff = new StringBuffer();
for (int i = 0; i<dataInput.length(); i++)
{
String result = (String)morseCode.get(dataInput.charAt(i));
//convert input data into morse code
buff.append(result+" ");
}
return buff.toString();
}
So i've changed a csv to xls/xlsx but i'm getting one character per cell. I've used pipe(|) as a delimiter in my csv.
Here is one line from the csv:
4.0|sdfa#sdf.nb|plplplp|plplpl|plplp|1988-11-11|M|asdasd#sdf.ghgh|sdfsadfasdfasdfasdfasdf|asdfasdf|3.4253242E7|234234.0|true|true|
But in excel i'm getting as
4 . 0 | s d f a
Here's the code:
try {
String csvFileAddress = "manage_user_info.csv"; //csv file address
String xlsxFileAddress = "manage_user_info.xls"; //xls file address
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split("|");
RowNum++;
HSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
The pipe symbol must be escaped in a regular expression:
String str[] = currentLine.split("\\|");
It is a logical operator (quote from the Javadoc of java.util.regex.Pattern):
X|Y Either X or Y
I was trying to export my C# list to Csv file. All is set well. But the thing is field seperator is not working properly. its showing like, my string with " at the end (eg: 0000324df"). Here is my Controller code.
IEnumerable stockexpo = stockexp; // Assign value
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("ItemNo,");
writer.Write("Repeat Count");
writer.WriteLine();
foreach (StockResult order in stockexpo)
{
writer.Write(String.Format("{0:d}", order.ItemNumber));
writer.Write("\"");
writer.Write(",");
writer.Write("\"");
writer.Write(order.Count);
writer.Write("\"");
writer.Write(",");
writer.WriteLine();
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "stockexp.csv");
I need to know how i can seperate the field values appropriately. Anyone can help me for this.
writer.Write("\"");
This line of code will be outputting a " every time. Why have it at all?
Also, I wouldn't have a comma before the WriteLine, since there is no need to delimit the end of the file.
IEnumerable stockexpo = stockexp; // Assign value
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("ItemNo,");
writer.Write("Repeat Count");
writer.WriteLine();
foreach (StockResult order in stockexpo)
{
writer.Write(order.ItemNumber);
writer.Write(",");
writer.Write(order.Count);
writer.WriteLine();
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "stockexp.csv");