I'm working on my second bigger programming project at the moment and I got stuck. I'm using Processing for this project.
What I'm trying to do is retrieve information (used to assign a certain color palette to the individual 'lines' of a horizontal bar chart) from an external text file that contains the following line, using an instance of the java.util.Properties class:
formating = p;p;n;n
My code snippet for importing it looks like this (using a class named 'Import' that handles the BufferedInputStream, etc.):
Import imp = new Import();
Properties properties = imp.importSettings();
The next step reads the 'formating' line from the text file and puts it into a four element String array, using the Semicolon as a delimiter.
String[] formating = properties.getProperty("formating").split(";");
I was expecting for this String array to be identical to the one I would get by creating it in my source code using:
String[] formating2 = {"p", "p", "n", "n"};
But it isn't. It tried a number of things already, including checking for unwanted characters (blanks for example) in each element of my String array, converting my text file or the characters I use for comparison to Unicode, converting the elements of the String array to Chars.
What I can't seem to get working is the following comparison:
for(int i=0;i < formating.length;i++){
println(formating[i]==formating2[i]);
}
which returns 'false' for each iteration of the for-loop.
I'm sure it's just some rookie mistake but it would be nice if someone could point me in the right direction. Thanks in advance!
Nick
comparing strings using == is not safe since Strings are possibly different objects and comparing them, no matter if they contain the same "text" does not compare the texts but the objects. So, you should try it like this:
println(formating[i].equals(formating2[i]));
or if you want to avoid excess spaces and tabs all-together you can also do:
println(formating[i].trim().equals(formating2[i].trim()));
Related
I'm reading a CSV file using Java. Inside the file, each row is in this format:
operation, start, end.
I need to do a different operation for different input. But something weird happened when I'm trying to compare two string.
I used equals to compare two strings. And one of the operation is "add", but the first element I fetched from the document always give me the wrong answer. I know that's an "add" and I printed it out it looks like an "add", but when I'm using operation.equals("add"), it's false. For all rest of Strings it's correct except the first one. Is there anything special about the first row in CSV file?
Here is my code:
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
String operation = data[0];
int start = Integer.parseInt(data[1]);
int end = Integer.parseInt(data[2]);
System.out.println(operation + " " + start + " " + end);
System.out.println(operation.equals("add"));
For example, it printed out
add 1 3
false
add 4 6
true
And I really don't know why. These two add looks exactly the same.
And here is what my csv file look like:
enter image description here
There are (at least) 4 reasons why two string that "look" like they are the same when you display / print them could turn out to be non-equal:
If you compare Strings using == rather than equals(Object), then you will often get the wrong answer. (This is not the problem here ... since you are using the equals method. However, this is a common problem.)
Unexpected leading or trailing whitespace characters on one string. These can be removed using trim().
Other leading, trailing or embedded control characters or Unicode "funky" characters. For example stray Unicode BOM (byte order mark) characters.
Homoglyphs. There are a number of examples where two or more distinct Unicode code points are rendered on the screen using the same or virtually the same glyphs.
Cases 3 and 4 can only be reliably detected by using traceprints or a debugger to examine the lengths and the char values in the two strings.
(Screen shots of the CSV file won't help us to diagnose this! A cut-and-paste of the CSV file might help.)
You should remove the double quotes from the first element and then check with equals method.
Try this:
String operation = operation.substring(1, to.length() - 1);
operation.equals("add")
Hope it works for you.
It looks like your line in image looks fine. I suppose in this case, that you could set wrong document encoding. E.g. when UTF, and you do not put it, then is has special header at the beginning. It could be a reason, why you read first word incorrectly.
I've been currently assigned to read from a .txt, and make a structure with what I've read. This is an example of what I should read:
Name1$Surname1$Programming&5.0#Mathematics&6.5#Algebra&7.2#History&6.7#Biology&6.9
I have no problems whatsoever when it comes to read the first two strings, however, from that point on i don't know how to manage, in order to properly split it and make new objects with them.
Any tips/ suggestions on how to do it pls?
Weird structure.
Split at '$'
First element of that split is the Name, second the Surname.
Split the third element at '#'.
Split each element of the result of step 3 again at '&' to get course and grade.
See here how to split strings.
I'm working on a piece of code where I've to split a string into individual parts. The basic logic flow of my code is, the numbers below on the LHS, i.e 1, 2 and 3 are ids of an object. Once I split them, I'd use these ids, get the respective value and replace the ids in the below String with its respective values. The string that I have is as follow -
String str = "(1+2+3)>100";
I've used the following code for splitting the string -
String[] arraySplit = str.split("\\>|\\<|\\=");
String[] finalArray = arraySplit[0].split("\\(|\\)|\\+|\\-|\\*");
Now the arrays that I get are as such -
arraySplit = [(1+2+3), >100];
finalArray = [, 1, 2, 3];
So, after the string is split, I'd replace the string with the values, i.e the string would now be, (20+45+50)>100 where 20, 45 and 50 are the respective values. (this string would then be used in SpEL to evaluate the formula)
I'm almost there, just that I'm getting an empty element at the first position. Is there a way to not get the empty element in the second array, i.e finalArray? Doing some research on this, I'm guessing it is splitting the string (1+2+3) and taking an empty element as a part of the string.
If this is the thing, then is there any other method apart from String.split() that would give me the same result?
Edit -
Here, (1+2+3)>100 is just an example. The round braces are part of a formula, and the string could also be as ((1+2+3)*(5-2))>100.
Edit 2 -
After splitting this String and doing some code over it, I'm goind to use this string in SpEL. So if there's a better solution by directly using SpEL then also it would be great.
Also, currently I'm using the syntax of the formula as such - (1+2+3) * 4>100 but if there's a way out by changing the formula syntax a bit then that would also be helpful, e.g replacing the formula by - ({#1}+{#2}+{#3}) *
{#4}>100, in this case I'd get the variable using {# as the variable and get the numbers.
I hope this part is clear.
Edit 3 -
Just in case, SpEL is also there in my project although I don't have much idea on it, so if there's a better solution using SpEL then its more than welcome. The basic logic of the question is written at the starting of the question in bold.
If you take a look at the split(String regex, int limit)(emphasis is mine):
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array.
Thus, you can specify 0 as limit param:
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
If you keep things really simple, you may be able to get away with using a combination of regular expressions and string operations like split and replace.
However, it looks to me like you'd be better off writing a simple parser using ANTLR.
Take a look at Parsing an arithmetic expression and building a tree from it in Java and https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Five+minute+introduction+to+ANTLR+3
Edit: I haven't used ANTLR in a while - it's now up to version 4, and there may be some significant differences, so make sure that you check the documentation for that version.
I'm very new to the world of Java programming, and although I know this is a ridiculously easy question, I can't seem to phrase my searches in a way that turns up the answer I need...so hopefully someone from this community won't mind helping me.
MY program needs to take an input line from a .csv file and split it into fields of an array, using commas as delimiters. The fields of the array are then assigned to variables that are different data types - char, int, float, and string. What I'm struggling with is the formatting for my String variables.
Here is part of my code:
public void parseCSV(String inputLine) {
String[] splitFields;
splitFields = inputLine.split(",");
try {
empNumber = Integer.parseInt(splitFIelds[0[);
payType = splitFields[1].charAt(0);
hourlyRate = Float.parseFloat(splitFields[2]);
last name =
I need to assign variable lastName, a String data type, to position 3 of my splitFields array. I just don't know how to format it. Help would be greatly appreciated!
A warning on your overall approach
Go with the other answers if you're doing a homework assignment with a simple csv file, but splitting a String on the comma character , will not work for more complicated CSVs. Example:
"Roberts, John", Chicago
This should be read as two cells where the first string is Roberts, John. Naive splitting on , will read this as three cells: "Roberts, John", and Chicago.
What you should be doing (for robust code)
If you're writing serious/production level code, you should use the Apache Commons CSV library to parse CSVs. There are enough tricky issues with commas and quotations, enough variation in possible formats that it makes sense to use a mature library. There's no reason to reinvent the wheel.
Another tool for parsing text
If you're a beginner, this might be opening up a can of worms, but a powerful tool for parsing/validating text input is "regular expressions." Regular expressions can be used to match a string against a pattern and to extract portions of a string. Once you have extracted a String from a specific cell of a csv, you could use a regular expression to validate that the String is in the format you're expecting.
While you're unlikely to really need regular expressions for this project, I thought I'd mention it.
String.split(...) returns a String[] so you really can just assign a specific index to a String.
String s = "one two dog!";
String[] sa = s.split(" ");
String ns = sa[1]; // ns now equals "two"
so you can just:
last_name = splitFields[index]; // this will work fine as long as index is within the `array` bounds.
Please mind that your last name var has a space(that might have been you problem).
I also recommend minding the parses, Integer.parseInt(...) & Float.parseFloat(...) might throw a NumberFormatException if you try to parse a non decimal values.
Easy, it is already a String, so you do not have to perform additional parsing. The following assignment will do the trick:
lastName = splitFields[3];
I've written a parsing program that appraises lists of information and appends the price at the end of the entry. I'm using HTMLUnit to get a string of the page I want to view using asText(). My code snippet reads as follows:
HtmlPage page = wc.getPage(name.substring(0, name.length() - 1));
wc.waitForBackgroundJavaScriptStartingBefore(100);
String test = page.asText();
In one of my cases, the string has an index count of 111,471 (according to the Eclipse debugger) and it ends in "...", which I'm assuming means this particular variable has no more space in the memory to store additional information. The string as is doesn't contain the entire webpage and the bit I need to extract is at the very bottom of the page. Is there a way I can parse strings of this size?
Are you sure that the string as is doesn't contain the entire webpage? Printing strings to the console can lead to ellipsis (or truncating, shown as ...) if the string is very long. That doesn't mean however, that it's cut off at the point of ellipsis.
Have you tried treating the string, and did you get any errors? Or do you just assume that it is incomplete?