I'm trying to check if a letter submitted by user is contained in a string, but it always return false. From what I read the .equals() function should work. I was expecting that if a user inputs the letter "a" it would return "pass" if the string was "america".
for (int i = 0; i < outputTest.length(); i++){
if (userInput.equals(outputTest.charAt(i))){
System.out.println("Pass");
}else {
System.out.println("Fail");
}
}
Based on outputTest.length() and outputTest.charAt() I am assuming that outputTest is String.
Based on userInput.equals I am assuming it is not primitive type like char (since primitive types don't have methods). It is also not Character, otherwise you would see Pass few times. So it most likely is also String.
outputTest.charAt(i) returns char, but you are comparing it with String which equals method looks like:
964 public boolean equals(Object anObject) {965 if (this == anObject) {966 return true;967 }968 if (anObject instanceof String) {969 String anotherString = (String)anObject;970 int n = value.length;971 if (n == anotherString.value.length) {972 char v1[] = value;973 char v2[] = anotherString.value;974 int i = 0;975 while (n-- != 0) {976 if (v1[i] != v2[i])977 return false;978 i++;979 }980 return true;981 }982 }983 return false;984 }
So since equals expects Object, char (returned from outputTest.charAt(i)) will be automatically boxed to Character, but since Character doesn't extend String test
if (anObject instanceof String)
will fail and you will immediately move to return false;.
You may want to use contains method if you want to check if one String contains another
outputTest.contains(userInput)
To find a string in another string, just do:
return text.contains(string);
To find a char in a string, do
return text.indexOf(ch) > -1;
What is the data type of your object userInput? You seem to be comparing a String object with a character which is returned by the charAt() method. That will always return false.
When you are learning to use methods, a good habit to develop is to look at what kind of data type the methods apply or return. For instance, you cannot code this: char scanner.nextLine() // nextLine() is to read String, not char. Therefore, in your code outputTest.charAt(i) // I am a char, and this userInput.equals() // I am a String, you are comparing different things. You cannot compare an apple with a desk because they are two different objects. The compiler will always tell you false.
I assume: String inputTest = scanner.nextLine(); for user input a letter, and you can consider "a" as a String with a length 1. (or any other letters inside)
if (outputTest.contains(userInput)) // now you are comparing String and String
System.out.println("Pass");
else
System.out.println("Fail");
Related
if(namefield.getText().compareTo("")==0)
Is this code above correct to check that no input is there in the textfield so that a error message can be generated?
provided have to use compareTo func only
to be more accurate
String data = nameField.getText()
if(data==null || data.length()==0)
{
//show error message here
}
It depends on how the namefield.getText() method is implemented in your platform. Since you didn't method which platform you are using. I suggest you can check the documentation.
Generally, when the namefield is not set, namefield.getText() will return a empty String which is "". So we don't need to check if it's null.
So we can check using following code:
if(namefield.getText().isEmpty()){}
which is same as following:
if(namefield.getText().length()==0){}
Because String.isEmpty() method is implemented as following:
public boolean isEmpty() {
return value.length == 0;
}
On the other hand, when the namefield.getText() can return null. You need to check null to avoid NPE.
String name = namefield.getText();
if(name==null || name.isEmpty()){}
Finally, if you want to check if the input string is whitespace, you can simply use String.trim() to remove the whitespace.
if(namefield.getText().trim().isEmpty()){}
or
String name = namefield.getText();
if(name==null || name.trim().isEmpty()){}
Even though we can use name.equals(""), I don't think it's the best way. Since in String.equals method, it firstly check if the objects are the same and then use the length to check if they're equal. However, when we get a text from a Textfield, the object will not be the same with the constant string "".
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
The method compareTo() is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.
Instead use equals()
if(namefield.getText().equals(null) || namefield.getText().equals(""))
{
//do this
}
I would use
if((namefield.getText()== null) || (namefield.getText().length() == 0)){
show error message
}
I am getting error saying "The type of the expression must be an array type but it resolved to String"
public class StringWord {
public static void main(String[] args) {
String s = new String("Ahmedabad");
int count = 0;
System.out.println(s.length());
for(int i = 0; i < s.length(); i++){
if(s[i].equals("A")||s[i].equals("a")||s[i].equals("e")||
s[i].equals("E")||s[i].equals("i")||s[i].equals("I")||
s[i].equals("o")||s[i].equals("O")||s[i].equals("u")||
s[i].equals("U"))
{
count++;
}
}
System.out.println("Vowels in a string: "+count);
}
}
if(s[i].equals("A")||s[i].equals("a")||s[i].equals("e")||s[i].equals("E")||s[i].equals("i")
||s[i].equals("I")||s[i].equals("o")||s[i].equals("O")||s[i].equals("u")||s[i].equals("U"))
equals method compares two strings. Here you want to compare character.
use s.charAt(i) instead of s[i] since you want to compare two characters. To get the character at the index i charAt(index) method can be used. Two compare two character == operator is used.
if(s.charAt(i)=='A'||s.charAt(i)=='E'||s.charAt(i)=='I'||s.charAt(i)=='O'||s.charAt(i)=='U')||s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u')
Your variable s is a String, but you treated it like an array by doing s[i].
You should use
s.charAt(i) // a method of String class which returns the char at the index i
instead of s[i].
Strings cannot be accessed by someString[index] (this notation is used for arrays).
Use charAt(index) instead, but note that charAt() returns a char, so you have to compare it with == not with equals() that is used for Strings.
You can also simplify this by:
if ("AaEeIiOoUu".contains(Character.toString(s.charAt(i))) )
{...}
Java String objects aren't character arrays, and you can't use array syntax with them. Instead, you need to use charAt, which returns a char, not a String like you're apparently expecting, and you would need to use == to compare primitives:
if(s.charAt(i) == 'a' || ...)
Additionally, you can use the indexOf method to dramatically simplify your if statement:
static final String VOWELS = "aeiouAEIOU";
for(int i = 0; i < s.length(); i++)
if(VOWELS.indexOf(s.charAt(i)) > -1
count++;
Yes. You are using String s here. There is no index there. Use char array from s. Or you can use s.charAt(index)
INCORRECT. PLEASE DISREGARD
You need to convert the string to an array.
s.ToCharArray();
Note: this is c# code, I don't know if it is similar to java.
I am attempting to create a method that checks every character in userInput to see if they are present in operatorsAndOperands. The issue is that tempbool is always false for all values.
import java.util.*;
public class stringCalculator
{
private String userInput = null;
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
public stringCalculator(String newInput)
{
userInput = newInput;
}
public boolean checkInput()
{
boolean ifExists = true;
for(int i=0; i<userInput.length(); i++)
{
char currentChar = userInput.charAt(i);
boolean tempbool = Arrays.asList(operatorsAndOperands).contains(currentChar);
if (tempbool == false)
{
ifExists = false;
}
}
return ifExists;
}
}
This is because you have an array of string objects (which you later convert to a list of string objects), but you are checking a char for presence in that array.
Efficiency is also pretty poor here - converting a fixed array to a list on each iteration takes a lot of unnecessary CPU cycles.
A simple solution to this problem is to put all characters in a string, and then check each incoming character against that string:
if ("0123456789+-*/".indexOf(currentChar) >= 0) {
... // Good character
}
Another solution would be making a regex that allows only your characters to be specified, like this:
if (expr.replaceAll("[0-9+/*-]*", "").length() == 0) {
... // Expr contains only valid characters
}
Why don't you declare
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
as a String, instead of an array of String. Then you can just use the contains method to check the characters against the valid operators.
Declare: char[] operatorsAndOperands; instead of: String[] operatorsAndOperands.
Or add this: String.valueOf(charToCompare) as the "contains" argument.
As has been pointed out, the issue is that you're checking for a char in a list of String objects, so you'll never find it.
You can make this check easier, though, by using a regular expression:
Pattern operatorsAndOperands = Pattern.compile("[0-9+\\-*/]");
My Object returns me - from
Log.d("FormattedDate", Object.getDOB());
if (!Object.getDOB().matches("[^-]*")) {
txtDOB.setText(Object.getDOB());
} else {
txtDOB.setText("-");
}
I am checking if my Object.getDOB() matches with -, then show emptry strings, but this regExp is not working.
java.lang.String has a String#contains() method that does this for you:
Returns true if and only if this string contains the specified
sequence of char values.
if (Object.getDOB().contains("-")) {
//code
}
You could also use
if (Object.getDOB().indexOf("-") != -1) {
//code
}
if it returns -1 then the string does not contain the char (in your case "-"). Otherwise it returns the index of the char.
You can use contains() in java to search which is available in String class
Returns true if and only if this string contains the specified
sequence of char values.
getDOB().contains("-")
SEE HERE
Basically what I'm trying to do is take a String, and replace each letter in the alphabet inside, but preserving any spaces and not converting them to a "null" string, which is the main reason I am opening this question.
If I use the function below and pass the string "a b", instead of getting "ALPHA BETA" I get "ALPHAnullBETA".
I've tried all possible ways of checking if the individual char that is currently iterated through is a space, but nothing seems to work. All these scenarios give false as if it's a regular character.
public String charConvert(String s) {
Map<String, String> t = new HashMap<String, String>(); // Associative array
t.put("a", "ALPHA");
t.put("b", "BETA");
t.put("c", "GAMA");
// So on...
StringBuffer sb = new StringBuffer(0);
s = s.toLowerCase(); // This is my full string
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
String st = String.valueOf(c);
if (st.compareTo(" ") == 1) {
// This is the problematic condition
// The script should just append a space in this case, but nothing seems to invoke this scenario
} else {
sb.append(st);
}
}
s = sb.toString();
return s;
}
compareTo() will return 0 if the strings are equal. It returns a positive number of the first string is "greater than" the second.
But really there's no need to be comparing Strings. You can do something like this instead:
char c = s.charAt(i);
if(c == ' ') {
// do something
} else {
sb.append(c);
}
Or even better for your use case:
String st = s.substring(i,i+1);
if(t.contains(st)) {
sb.append(t.get(st));
} else {
sb.append(st);
}
To get even cleaner code, your Map should from Character to String instead of <String,String>.
String.compareTo() returns 0 if the strings are equal, not 1. Read about it here
Note that for this case you don't need to convert the char to a string, you could do
if(c == ' ')
use
Character.isWhitespace(c)
that solves the issue. Best practice.
First, of all, what is s in this example? It's hard to follow the code. Then, your compareTo seems off:
if (st.compareTo(" ") == 1)
Should be
if (st.compareTo(" ") == 0)
since 0 means "equal" (read up on compareTo)
From the compareTo documentation: The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal;
You have the wrong condition in if (st.compareTo(" ") == 1) {
The compareTo method of a String returns -1 if the source string precedes the test string, 0 for equality, and 1 if the source string follows. Your code checks for 1, and it should be checking for 0.