Is there a way to make sure that the + plus operator is used to concatenate a String as opposed to being used as an arithmetic operator, for example this won't work because inGame is a boolean and e.getSource() == list is also a boolean.
System.out.println((e.getSource() == list) + inGame);
but
System.out.println(e.getSource() == list +""+ inGame);
this will, is there someway for the top example to work e.g. a way to tell the compiler to use the operator as concatenate operator as opposed to the arithmetic one ?
You could use a StringBuilder to concatenate your Strings (and other stuff) properly. After all, that's what internally Java does when you use the "+".
System.out.println(new StringBuilder().append(e.getSource() == list).append(inGame).toString());
You can use String.valueOf():
System.out.println(String.valueOf(e.getSource() == list) + String.valueOf(inGame));
Or, if you're just printing:
System.out.print(e.getSource() == list);
System.out.println(inGame);
Lastly, printf() is also an option:
System.out.printf("%b%b\n", e.getSource() == list, inGame);
This is useful if you're trying to print in more complicated formats.
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)
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've been getting an "illegal start of expression" error when trying to compile this for loop inside a if statement in java. Does anyone have any idea why?
if(letter.equals(" ") || letter == null ||for(String a: array){ letter.equals(a);})
Try
if( letter == null || letter.equals(" ") || checkArray(array, letter))
{
...
}
boolean checkArray(String[] arryay, String letter)
{
for(String a: array)
if(letter.equals(a))
return true;
return false;
}
Note: checking letter for null after you have already called equals() does not make too much sense; i've reordered those.
You cannot. Perhaps you should move the if statement into the for statement?
As rfausak said, a for statement does not return a boolean. You should have made that an answer by the way.
If you use a Set you could write:
if ( (letter.equals(" ")) || (letter == null) || (a.contains(letter)) ) {}
Well, that´s because you can not have a for loop within an if condition. It seems you want to see if the letter is within the array array; if so then you can do it with Apache commons-lang's ArrayUtils:
ArrayUtils.contains( array, letter );
This wont work because a for doesn't evaluate to a boolean. For readabilities sake you should extract that to a method anyway, good examples appear in other answers.
Other points, you should rejig your conditionals to not be susceptible to NullPointerExceptions
if (letter == null || " ".equals(letter) || arrayContains(array, letter)) {
//...
}
If you are able to add additional libraries, there are some nice apache commons libraries to make this work easier, namely StringUtils in commons-lang and CollectionUtils in commons-collections.
You also may like to harden that input checking if it's possible to get Strings larger than one character, by using String#trim() after checking for null. Again, this would be a good candidate for an extracted method isBlank(String str).
So I'm reading input from a file, which has say these lines:
NEO
You're the Oracle?
NEO
Yeah.
So I want to output his actual lines only, not where it says NEO. So I tried this:
if(line.trim()=="NEO")
output=false;
if (output)
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the line if 'output' is true
But thats not working out. It still prints NEO. How can I do this?
When comparing strings in Java you have to use the equals() method. Here's why.
if ( "NEO".equals(line.trim() )
I think you're looking for line.trim().equals("NEO") instead of line.trim() == "NEO"
That said, you can get rid of the output variable by instead doing
if(!line.trim().equals("NEO"))
{
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the if it isn't "NEO"
}
Strings are objects in Java. This means you can't just use the == operator to compare them, since the two objects will be different even if they both represent the same string. That's why the String object implements an equal() method, which will compare the contents of the objects, instead of just their memory addresses.
Reference
String.equals() docs
In Java, Strings are objects. And the == operator checks for exact equality.
In other terms
final String ans = line.trim();
final String neo = "NEO";
if (ans == neo) ...
implies you want to check that the ans and the neo objects are the same. They are not, since Java allocated (instantiated) two objects.
As other said, you have to test for equality using a method created for the String object, that actually, internally, checks the values are the same.
if (ans.equals(neo)) ...
try the following:
if(line.trim().equals("NEO"))