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.
Related
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.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to make a simplified version of Black Jack in Java using eclipse. I'm trying to make it so the player types 'hit' or 'stand', and while they haven't, it keeps prompting them to do so.
while (hitorstand != ("hit") || hitorstand != ("stand"))
{
System.out.println("Would you like to hit or stand?(1 for hit, 2 for stand)");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
}
if (hitorstand.equals("hit"))
{
playercard3 = random.nextInt(10) +2;
System.out.println(""+playercard3);
}
else if (hitorstand.equals("stand"))
{
System.out.println("You had a total value of " + playercardtotal + ".");
if (hiddendealercard == card2)
When I run it, no matter what I type it cannot escape the while loop. I know it would work if I used numbers but I really want to learn how to use words as input.
while (hitorstand != ("hit") || hitorstand != ("stand")) // This is not the right way
Use the equals() method for String value comparison. == is for object reference comparison.
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")) // This is
I'm not sure why you'd use the != in the while loop condition, whereas you've properly used (hitorstand.equals("hit")) just below the while, in a if statement.
Also, there seems a minor mistake in the while loop block.
hitorstand.toLowerCase(); // This does nothing
As Strings are immutable in java, you need to assign back the changed string to be able to see the changes
hitorstand = hitorstand.toLowerCase(); // Assigning back the lowercase string back to hitorstand
You need to use .equals(..) instead of ==. This is because == is used for reference equality, while .equals() is simply for value equality.
For example:
while(!hitorstand.equals("hit") || !hitorstand.equals("stand"))
Comparing hitorstand != ("hit") you actually compare object references not the String value itself. To compare strings you need to use equals method. In java every class inherits equals ( from Object ) and it can be overriden for custom object comparison
Try this:
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")){
Adding to the answers, a good rule of thumb is to use .equals() with strings and == with integer values or variables with integer values (or the value null).
One way you could do this would be to use a character. For example: instead of
while (hitorstand != ("hit") || hitorstand != ("stand"))
you could have it check for the first character in the string using the charAt() command with the index of the string in the parenthesis. So since your looking for the first character, it would be at index 0.
while (x != 'h' || x != 's')
x being a char.
Inside your while loop,
System.out.println("Would you like to hit or stand?");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
x = x.charAt(0); // you would just add this line. This gets the character at index 0 from the string and stores it into x. So if you were to type hit, x would be equal to 'h'.
Your if statement could stay the same or you could also change the condition to (x == 'h') and (x == 's'). That's up to you.
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));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String is not equal to string?
I'm new to java and I can't figure out what's wrong with this code block.
I know the array isn't null I'm testing it elsewhere. Maybe there is a syntax problem I'm used to program in c#.
Scanner input = new Scanner(System.in);
System.out.println("Enter ID :");
String employeeId = input.nextLine();
int index = -1;
for(int i = 0 ; i < employeeCounter ; i++)
{
if(employeeId == employeeNumber[i])
{
index = i;
}
}
if(index == -1)
{
System.out.println("Invalid");
return;
}
I always get to the 'Invalid' part. Any idea why ?
Thanks in advance
employeeNumber[0] is "12345"
employeeId is "12345"
but I can,t get into the first if statement although employeeId IS equal to employeeNumber[0].
Don't compare strings with ==.
Use
if (string1.equals("other")) {
// they match
}
Compare strings like that
if(employeeId.equals(employeeNumber[i]) {
}
As others have pointed - full code will be helpful, but my guess would be this line of the code:
if(employeeId == employeeNumber[i])
You don't compare 2 strings by using ==. Use equals() or equalsIgnoreCase() instead. == only checks for object equality i.e. are employeeId and employeeNumber referencing to the same object in memory. So, for objects always use the equals() method..for Strings you can also use equalsIgnoreCase() for a case insensitive match. == should be used on primitive types like int, long etc.
When you use == with two string, it compares pointer addresses
You should use firststring.equals(secondstring) in order to compare two strings
Use equals() method to compare Strings
if(employeeId.equals(employeeNumber[i])){}
When you compare strings, use
String1.equals(String2);
This should give you the result
"==" checks whether the reference for two objects are same. But equals() method checks whether the content is same or different.
I was asked for my homework to make a program wherein the user inputs a Roman numerals between 1-10 and outputs the decimal equivalent. Since I'll be getting a string in the input and an integer in the output, I parsed it, but it won't work. Any ideas why?
import java.util.Scanner ;
class Romans {
static Scanner s = new Scanner(System.in) ;
static String val = null ;
public static void main (String [] args)
{
System.out.print ("Enter a roman numeral between I to X: ");
String val = s.nextLine();
int e = Integer.parseInt(val);
}
static int getRoman (int e)
{
if (val = "I"){
System.out.print ("1") ;
}else if (val = "II" ){
System.out.print ("2") ;
}else if (val = "III") {
System.out.print ("3") ;
} else if (val = "IV") {
System.out.print ("4") ;
} else if (val = "V"){
System.out.print ("5");
} else if (val = "VI") {
System.out.print ("6");
} else if (val = "VII") {
System.out.print ("7");
} else if (val = "VIII") {
System.out.print ("8");
} else if (val = "IX") {
System.out.print ("9");
} else if (val = "X") {
System.out.print ("10") ;
}
return val ;
}
}
Two points:
= is the assignment operator, not the equality-testing operator (==)
You shouldn't use == to test for string equality anyway, as it will only test for reference equality; use equals to test whether two string references refer to equal (but potentially distinct) string objects.
Additionally, you're trying to return a String variable as an int, and you're not even calling getRoman...
I think we can tell you that the correct way to compare Strings is using equals().
You're doing assignments, to compare primitive types you've to use ==, to compare String the equals method.
Example:
if (val.equals("I"))
But also val is not present in the method getRoman().
You are trying to parse val as an int, but its not, its a character.
For such a small sample of chars, its probably easiest to simply create a lookup table, index it on the char.
Are you getting any errors?
In your code, you never call the getRoman function. Also, you're using the assignment operator = instead of the comparison operator "I".equals(val) for example.
String comparsion should be done with equals(String str) method instead of == comparison.
PS. You have = instead of == anyway.
The following statement is an assignment:
val = "I"
That is definitely not what you want to do here.
A comparison is done with the double equals, but double equals (==) compares references but you do not want to do that here either.
You want to use the equals method.
if (val.equals("I")) ...
Make those change everywhere and see how it works for you.
ACtually your main trouble comes from string comparison. In java, = is meant to assign values to variables, == is meant to compare values of primitive types and equals is the way to compare objects, especially for strings.
An alternative to using equals can be to use the JDK internal pool of strings, in this case, you could use == as a comparator.
In your case of parsing roman language numbers, you could also consider using a hashmap to store and retrieve effectively the parsed values of numbers. If you have thousands of comparisons like this to make, then go for identityhashmap.
And last, if you want to do real parsing for all roman numbers, not only the first ones, then you should considering using an automata, i.e. a state machine to parse numbers in a somewhat recursive way, that would be the more efficient model to apply to your problem.
The last 2 remarks are more oriented towards software algorithms, the first two ones are more oriented towards java syntax. You should start to know the syntax before going higher level optimizations.
Regards,
Stéphane
Aside from what was said above about how your String comparison should use the equals( ... ) function - for example,
if ( val.equals("VII") )
you also need to provide a return value for your function called getRoman. This function was declared as a function that returns an integer value to the caller, but in the implementation that you have provided, there are no return values (only System.out.println( ... )).
Also, you aren't inputting the correct parameter type - from what it looks like, your function is checking a String to see if it is a certain Roman numeral. So the correct function header would look like this:
public static int getRoman(String val)
Also, make sure you are actually calling this function in your main() - from what it looks like right now, you aren't even using the getRoman() function.
Hope this helps!