I want to read a data stream and everytime it reads a certain word or phrase I want the count to go up. The example I have below fails to count it. I tried looking for "echo percent" as well. All the bat file does is echo percent.
try {
String ls_str;
String percent = "percent";
Process ls_proc = Runtime.getRuntime().exec("c:\\temp\\percenttest.bat");
// get its output (your input) stream
DataInputStream ls_in = new DataInputStream(ls_proc.getInputStream());
while ((ls_str = ls_in.readLine()) != null ) {
System.out.println(ls_str);
progressBar.setValue(progress);
taskOutput.append(String.format(ls_str+"\n", progress));
if (ls_str == percent) {
progress++;
}
}
} catch (IOException e1) {
System.out.println(e1.toString());
e1.printStackTrace();
}
setProgress(Math.min(progress, 100));
DataInputStream.readLine is deprecated. Use BufferedReader and its readLine method or Scanner and nextLine instead. Also, use .equals to compare two strings, not ==.
The == comparison only does a reference comparison, asking the question, "Are these two strings in the same place in memory?" Usually, the answer is "no." On the other hand, equals asks the question, "Are the characters in these two strings the same?" This is called deep comparison, and the == operator doesn't perform the deeper comparison.
Don't compare the Strings with ==, use the equals method.
If you compare the Strings with ==, you're checking to see if they're the same String.
If you compare them with equals, you're checking whether or not their contents are the same.
Instead of:
if (ls_str == percent)
Do this:
if (ls_str.equals(percent))
If you want to ignore case, you can do it like this:
if (ls_str.equalsIgnoreCase(percent))
EDIT
Your String format is also messed up.
Change:
taskOutput.append(String.format(
ls_str+"\n", progress));
to:
taskOutput.append(String.format(
ls_str+"\n"), progress);
Notice the parentheses change.
Take a look at these for more explanations:
Java String.equals versus ==
http://www.java-samples.com/showtutorial.php?tutorialid=221
Related
Can you split a string in Java without storing what has been split into variables? (Assignment requirement :()
I have tried things which worked on other programming languages however nothing I try seems to work:
(Attempting to see if the second item in a space delimited string (x) is +)
if ((x.split.(" ")).(1) = "+") {
// Do something
}
if ((x.split.(1).(" ")) = "+") {
// Do something
}
Well, what is returned is of type String[]. So if you know that there will be two items, you can reference it as an array..
if(x.split(" ")[1].equals("+"))
Extra Reading
You should look at String Comparison.
String.split returns an array, so this is how it could be done. Note the use of '.equals()'. In Java the == operator checks if the pointer value is the same.
if (x.split.(" ")[1].equals("+")) {
// Do something
}
(And of course this could throw an out of bounds exception if the split wouldn't make an array of size >= 2)
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
(Sorry for the weird title, but I can't figure out what actually the problem is)
The following code should get a String from the command line first (which works), then the input is being splitted (works perfectly, too; I checked by printing both Strings before the if/else as you can see in the part I commented out again) and then it should check what the first part of the splitted String is. And for example if it equals "tweet" it should procedure with the Tweet method.
But somehow it doesn't get that right. It always executes the else statement...
Scanner sc = new Scanner(System.in);
System.out.print("> ");
String input = sc.nextLine();
String[] splitString = input.split(" ");
if(splitString.length != 2){ throw new IllegalArgumentException(); }
String command = splitString[0];
String value = splitString[1];
/*System.out.print(command);
System.out.print(value);*/
if(command == "tweet") { Tweet(value); }
else if(command == "help") { ShowHelp(); }
else { System.out.println("Command "+command+" not found."); }
I tried entering "tweet asdf", but it returns
> tweet asdf
Command tweet not found.
What did I do wrong? I'm confused D:
Use the .equals method instead of ==.
== compares the references. .equals will compare the actual content of the two strings.
When comparing strings, you will almost always want to use .equals not == as usually you are wanting to compare content, not reference.
You're using == to compare two objects. This compares their references. Use if(command.equals("tweet")) instead to compare by values.
Due to string interning depending on the JVM and implementation(official classpath, GNU classpath, etc) your approach may operate properly hit-or-miss.
I've got this code:
Scanner inputScanner = new Scanner(System.in);
String word;
do
{
word = inputScanner.next();
System.out.println(word + ": " + dict.contains(word));
}
while (word != "#");
It's pretty straight-forward, but the loop is NOT terminating after receiving a # input from the user. I've seen other people complaining that Scanner is error-prone and can give unexpected results, but that doesn't explain why dict.contains(word) functions perfectly while the while (word != "#") condition is not doing a thing...
What gives?
You are using == to compare strings; use String#equals instead.
...
while (!word.equals("#"));
You need to use the .equals() method rather than the == operation. "==" operations are used to compare primitives like boolean, int, long, ect and references.
A String is an object so Java assumes you want to compare the reference value rather than the value contained in the string. Also remember that you cannot compare Long, Integer, Double ect with the == operator either.
I have a strange problem when adding a value to a String array which is later involved in an array sort using a hash map. I have a filename XFR900a, and the XFR900 part is added to the array using the following code;
private ArrayList<String> Types = new ArrayList<String>();
...
Types.add(name.substring(0,(name.length() - 1));
System.out.println(name.substring(0,(name.length() - 1));
I even print the line which gives "XFR900", however the array sort later on behaves differently when I use the following code instead;
Types.add("XFR900");
System.out.println(name.substring(0,(name.length() - 1));
which is simply the substring part done manually, very confusing.
Are there any good alternatives to substring, as there must be some odd non ascii character in there?
Phil
UPDATE
Thanks for your comments everyone. Here is some of the code that later compares the string;
for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last == matchedArray.get(i)) {
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));
As you can see I have added a test System.out.println("DO NOT MATCH" ... and below is some the output;
DO NOT MATCH :FR99-XFR900
DO NOT MATCH :XFR900-XFR900
I only run the substring on the XFR900a filename. The problem is that for the test line to be printed last != matchedArray.get(i) however they are then the same when printed out to the display.
Phil
You should never use the == operator to compare the content of strings. == checks if it is the same object. Write last.equals(matchedArray.get(i)) instead. The equals() method checks if to object are equal, not if they are the same. In case of String it checks if the two strings consists of the same characters. This might eliminate your strange behaviour.
PS: The behaviour of == on string is a little unpredictable because the java virtual machine does some optimization. If two strings are equal it is possible that the jvm uses the same object for both. This is possible because String objects are immutable anyway. This would explain the difference in behaviour if you write down the substring manually. In the one case the jvm optimizes, in the other it doesn't.
Use .equals() rather than == because they are strings!
if (last.equals(matchedArray.get(i))) {}
Never use == operator if you wanted to check the value since operator will check the Object reference equality, use equals operator which check on the value not the reference i.e. for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last.equals(matchedArray.get(i))) { // Line edited
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));
I have an array in containing numbers that represent cable sizes (1, 1.5, 2.5, etc), stored as strings.
In my program, the array is loaded into a spinner, which is working fine.
However, when the item is selected and stored in a variable, I want to check what string was selected, and set another numerical variable to 2.5 so I can do a calculation later in the program.
I tried the following:
if (conductorSize = "1" ) {conCsa = 1;}
else if (conductorSize = "1.5") {conCsa = 1.5;}
conductorSize being the variable holding the selected string, and conCsa being the variable
set to a numerical variable for calculation.
The compiler says that I cannot convert a string to boolean. What's happening?
If you are doing string comparisons, use .equals()
Example taken from here:
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT <<<<<<<<<<<<< Use this.
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
As Ed S. points out you are using the assignment operator. However since you are comparing a String you need to use the equals method.
if ("1".equals(conductorSize)) {conCsa = 1;}
else if ("1.5".equals(conductorSize)) {conCsa = 1.5;}
Alternatively, you could just create a new float from your String:
float conCsa;
try {
conCsa = Float.parseFloat(conductorSize);
}catch(NumberFormatException e){
conCsa = 0.0f; //set to a default value
}
It looks like what you're trying to do might better be expressed in this way:
conCsa = Double.parseDouble(conductorSize);
In general you need to use the .equals() method.
If performance is extremely important and you are comparing against string literals, take a look at String.intern(). It'll allow you to do super-fast == comparisons and avoid a full character-by-character scan as in .equals().
Performance would have to be really, really important though, to justify such a non-standard approach.
When you have cable sizes which are constants, you need to use Enums , which will help you in reducing no of if condition comparisons.