What does it mean if something is equal to -1? - java

Can anyone explain to me what it means?
Example:
for(char ch : (a+b).toCharArray()){
if(a.indexOf(ch) == -1 || b.indexOf(ch) == -1){
...
}
}
I want to understand the meaning of -1.

a.indexOf(ch) == -1:
It means that the character ch is not found in string a
Extended explanation:
indexOf() : This method returns the index within this string of the first occurrence of the specified character or -1, if the character does not occur.

-1 if it never occurs.
learn more about the method here -
https://www.w3schools.com/java/ref_string_indexof.asp

Related

Finding the first index of a vowel in a given string, otherwise return -1 if there aren't any

So I'm trying to practice writing code by hand for a coding exam, and one of the sample questions is to find the index of the first vowel in a given string, if there are none, return -1.
I tried putting this in eclipse and debugged this. I don't understand why this doesn't work. I keep getting 101 as an output. Initially I didn't use the index variable, I had the if statement return word.charAt(i). I tried changing that and it didn't do anything.
(For exam purposes, they wanted us to just use lowercase vowels)
Also if you had to write this, what would be an easier way to write this?
public static int firstVowel(String word) {
for (int i = 0; i < word.length(); i++) {
int index;
if (word.charAt(i) == 'a' || word.charAt(i) == 'e' || word.charAt(i) == 'i' || word.charAt(i) == 'o'
|| word.charAt(i) == 'u') {
index = word.charAt(i);
return index;
}
}
return -1;
}
You're getting the int repesentation of the char, you actually want to return i as this shows the position where you found the char.
The problem here is that you are storing word.charAt(i), which returns a character value, into index, which stores an integer.
I believe that when you store a char value in an integer variable that what you're really storing is the ASCII value of the character. 101 represents 'e' on an ASCII table, so what is happening here is that you're detecting an 'e' at index i, and then storing its ASCII value in index and returning index.
To solve your problem, you don't really need the index variable at all. You simply need to return i within your if-statement.

Why won't my code compile which checks if a string begins with vowel?

if (flipped.charAt(0) = "a" || "e" || "i" || "o" || "u"){
paren = "(" + flipped;
String firstpart = paren.substring(0,5);
String rest = paren.substring(5);
System.out.println(rest+firstpart);
}
In this code, I'm looking to check if the first character of String flipped is a vowel. If it is, I'm adding a parenthesis to the beginning and moving the first 5 characters to the end of the string. Eclipse is giving me java.lang.NullPointerException and saying that "The left-hand side of an assignment must be a variable." What can I do to fix this?
Your code has following issues,
Use conditional operator == instead of assignment = at if statement.
Use single quotation ' instead of double " for char
Make a separate method for vowel check.
boolean isVowel(char ch){
ch=Character.toLowerCase(ch);
return ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u';
}
Another very simple solution I often use:
if ("aeiou".indexOf(Character.toLowerCase(text.charAt(0))) >= 0) {
// text starts with vocal.
}
You can also use regular expression matching:
if (text.matches("^[aeiou].*")) {
Use a collection that holds all of these values.
Set<Character> myList = new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
if(myList.contains(Character.toLowerCase(flipped.charAt(0)))) {
// Do work
}
This line of code (while wrong: = will assign, == will compare)
if (flipped.charAt(0) == "a" || "e" || "i" || "o" || "u"){
will first compare flipped.charAt(0) == "a" which returns a boolean. Then it will continue with boolean || "e" || "i" || "o" || "u".
boolean || "e" is not valid code.
The accepted answer although explained the problem didn't quite show the solution for how he was checking the problem. So I figured i'd show a corrected solution as well as offer my own solution to such a problem.
Someone who cannot understand Boolean compare syntax isn't going to understand All those special classes. Not to mention some of those needs imports he may not have and will now need to understand why he's getting errors. I assume this person has came to a resolution by now given it's been 5 years.. but in the evnet someone else or even this person still is unsure on something.
Your Original Code Updated ( I removed the contents inside as I don't know what they do or if they were accurate ).
char c = flipped.charAt(0);
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' ||
c == 'I' || c == 'o' || c == 'O' || c == 'U' || c == 'u')
{
Now this supports checking if "flipped.charAt(0)" equals a vowel weather lower case or uppercase. As you can see we do a Boolean check for each situation by checking if "C" equals something else. You only offered the check one time so the syntax error was because of that you were doing Boolean checks on non Boolean values. When you have values next to "||" it must be "false", "true" or "SomethingA == SomethingB". If that something is an object you typically have to do "SomethingA.equals(SomethingB); E.g. byte,int,short,long,float,double will all work just fine, but String would require the second method.
Below are some tips to reduce this further.
We can force char "c" to lowercase by doing any of the below methods.
char c = Character.toLowerCase(flipped.charAt(0));
Or we can do a more clever way.
char c = flipped.charAt(0) | 32;
As such now we only need to do the following to check if it's a vowel.
char c = flipped.charAt(0) | 32;
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' ||c == 'u')
{
However we can take this a step further.
We can reduce the code even more!
if (((1 << flipping.charAt(0)) & 2130466) != 0)
{
So basically how my final solution works. Unfortunately it's pretty involved to explain it, but i'll try my best.
In any programming language you have values of Byte, Short, Int, and Long these are 8bit, 16bit, 32bit, and 64bit respectively.
When you perform 1 << N you are doing 2^N which is basically the power of two method. The thing is though when you use this on the Byte, Short, Int, or Long the value "N" is reduced.
So.. (keep in mind different languages handle these differently).
Byte can only range from 0-7.
Short can only range from 0-15.
Int can only range from 0-31.
Long can only range from 0-63.
So now we know letters have a value A-Z = 65-90 and a-z = 97-122 when we do 1 << letter it will actually be 1 << (1-26) because the those numbers module or remainder of 32 is 1-26 in both cases.
You can see this by doing the following.
A = 65.
65-32=33.
33-32=1. Stop.
So now we know A will equal 1 in this situation.
So now we do 1 << 1 or 2^1 = 2. So the letter A gives us the value "2".
Repeat this for all the vowels and we can a sum of bit values. Bit values are just powers of two added together. I again really can't go hard explaining this it's pretty involved but hopefully you kind of have an idea.
Now what we are doing is taking the sum of the vowel bits and comparing it to the number 2130466 which contains the bit values of A,E,I,O,U already. If those bit value we check for happens to exist in 2130466 then it must be A,E,I,O,U and as such it's a vowel.
The return result is 0 or the value so we simply check that this value doesn't equal 0.
Please keep in mind if anyone uses this that this assume you know the letter will be A-Za-z situation because if it was for example a "!" this will return a false positive as a "A" vowel. You can solve this by prechecking if the value is below "A" and above "u" and return out early.

get wrong output of a recursive method

public static int getIndexOf(char ch, String str) {
if (str == null || str.equals("")) {
return 0;
//base case
}else{
char first = str.charAt(0);
if (ch != first) {
return -1;
//returns -1 when the character cannot be found within the string
}else{
int rest = str.length() - 1;
if (str.charAt(rest) == ch) {
return rest;
}
return lastIndexOf(ch, str.substring(0, rest));
//recursive case
}
}
}
This my method which returns the index of the input character of the input string. However, when I run it in the interaction plane, it returns wrong number. For example, when I enter 'a' and "peach", it is supposed to return 2, but it returns -1. This method should return -1 only when the character cannot be found in the string. Can anyone tell me how to deal with it?
Thank you!
Well why don't you step through the logic and see what happens.
getIndexOf('a', "peach")
Method goes in, string isn't null or empty so it falls through to the next line of code.
char first = str.charAt(0); // this is 'p'
if (ch != first) { // is 'p' equal to 'a'? no. so return -1
return -1;
And then the rest of your logic will never execute. Can you see how to fix this problem?
your following portion of code means that it will check for the first character of the string if it is matching otherwise it will return -1.
char first = str.charAt(0);
if (ch != first) {
return -1;
this says that if character at 0th index doesn't match then send -1 so as 'p' in "peach" isn't matching with 'a' so it is return -1.
did you get it?
The output's not wrong, the implementation is!
Think in words first. If the desired character is the first character in the string, then the result is zero. Otherwise it's (1 + the index in the string that remains after cutting off the first character). Now code the words:
return (str.charAt(0) == ch) ? 0 : 1 + getIndexOf(ch, str.substring(1));
This doesn't yet handle the case where the character is not in the string at all. Here the charAt(0) call will eventually throw IndexOutOfBoundsException because str doesn't have one!
The cleanest way to handle this case is to catch the exception. So you's have two functions: mustGetIndexOf, which is the recursive relation above, and getIndexOf, which calls the one above inside a try {} catch() {}, returning -1 in that case.
Of course if you don't want to allow the exception, you can test the recursive call's result with if for the special case of -1. The code is uglier, but it will work. Whenever a -1 is seen, return -1 again. This propagates the -1 all the way back to the caller. The exception "unwinds" the recursive calls on the stack in a similar manner, just with one chop instead of the gradual call-by-call way your if statements will do it.
I won't give you full code so you can continue to learn.

How do I compare a character to check if it is null?

I tried the below, but Eclipse throws an error for this.
while((s.charAt(j)== null)
What's the correct way of checking whether a character is null?
Check that the String s is not null before doing any character checks. The characters returned by String#charAt are primitive char types and will never be null:
if (s != null) {
...
If you're trying to process characters from String one at a time, you can use:
for (char c: s.toCharArray()) {
// do stuff with char c
}
(Unlike C, NULL terminator checking is not done in Java.)
Default value to char primitives is 0 , as its ascii value.
you can check char if it is null. for eg:
char ch[] = new char[20]; //here the whole array will be initialized with '\u0000' i.e. 0
if((int)ch[0]==0){
System.out.println("char is null");
}
Correct way of checking char is actually described here.
It states:
Change it to: if(position[i][j] == 0)
Each char can be compared with an int.
The default value is '\u0000' i.e. 0 for a char array element.
And that's exactly what you meant by empty cell, I assume.
You can use the null character ('\0'):
while((s.charAt(j)=='\0')
I actually came here from reading a book "Java: A Beginner's Guide" because they used this solution to compare char to null:
(char) 0
Because in ASCII table, null is at the position of 0 in decimal.
So, solution to OP's problem would be:
while((s.charAt(j) == (char) 0)
I also tried out the already offered solution of:
while((s.charAt(j)=='\0')
And it also worked.
But just wanted to add this one too, since no one mentioned it.
If s is a string and is not null, then you must be trying to compare "space" with char. You think "space" is not a character and space is just null, but truth is that space is a character. Therefore instead of null, use (which is a space) to compare to character.

Checking a character within a String

I have this code
if(!(lotNo.charAt(0) >= "0" && (lotNo.charAt(0) <= "7"))) {
// if the first character is not within these boundaries
return false;
}
return true;
This method leaves me with an error saying bad operator type? Although it was supposed to check whether the first character in a String was between 0 and 7. Am I on the right lines?
Char must be within '0' not "0". The second one is a String
You are comparing to strings instead of chars. Try:
if (!(lotNo.charAt(0) >= '0' && (lotNo.charAt(0) <= '7'))) { // if the first character is not within these boundaries
return false;
}
return true;
"0" <-- String with one char, '0'
'0' <-- char, the character '0'
charAt(int index) method return value type is char .
But you are comparing it with a String that's why you get bad operator type

Categories