Checking a character within a String - java

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

Related

String index out of range - java

What does that mean? The length of the string is too long or there is error in my code?
public class Program {
public static String flipEndChars(String s) {
if(s.charAt(0) == s.charAt(s.length())){
return "Two's a pair.";
}
else if(s.length()<3){
return "incompatible";
}
else
return s.charAt(s.length()) + s.substring(1,s.length()) + s.charAt(0);
}
}
the issue is with this part :
s.charAt(s.length())
It's trying to access a character beyond the length of your string. The indexation is zero based, so the last character of a string is always at index s.length() - 1
String.charAt(int) returns the char at the specified index, where 0 is the first character, 1 is the second character, 2 is the third, and so on.
"hello".charAt(0) returns the character h.
String.length() returns the length of the string.
"hello".length() returns 5. So if you call "hello.charAt(5)", this will get the 6th character in the String "hello", which does not exist. This will throw an IndexOutOfBoundsException.
I hope this helps.

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.

how to tell whether a string contain a specific amount of characters with Array?

one of my homework problem is
Define a method named countAll that accepts a String as an argument.The method must
return an array of int of size 27, such that the value in position 0 is a count of the number of
‘a’ and ‘A’ characters in the input, the value in position 1 is a count of the number of ‘b’ and
‘B’ characters in the input, … the value in position 25 is a count of the number of ‘z’ and ‘Z’ characters in the input, and the value in position 26 is a count of all the non-alphabetic
characters in the input.
i tried solving it with
public static int[] countAll(String input){
int[] ints = new int[27];
for(int i=0;i<input.length();i++){
if(input.charAt(i)=='a'||input.charAt(i)=='A'){
ints[0]+=1;
}
if(input.charAt(i)=='B'||input.charAt(i)=='b'){
ints[1]++;
}
if(input.charAt(i)=='c'||input.charAt(i)=='C'){
ints[2]++;
}
if(input.charAt(i)=='d'||input.charAt(i)=='D'){
ints[3]++;
}
if(input.charAt(i)=='e'||input.charAt(i)=='E'){
ints[4]++;
}
if(input.charAt(i)=='f'||input.charAt(i)=='F'){
ints[5]++;
}
if(input.charAt(i)=='g'||input.charAt(i)=='G'){
ints[6]++;
}
if(input.charAt(i)=='h'||input.charAt(i)=='H'){
ints[7]++;
}
if(input.charAt(i)=='I'||input.charAt(i)=='i'){
ints[8]++;
}
if(input.charAt(i)=='j'||input.charAt(i)=='J'){
ints[9]++;
}
if(input.charAt(i)=='K'||input.charAt(i)=='k'){
ints[10]++;
}
if(input.charAt(i)=='l'||input.charAt(i)=='L'){
ints[11]++;
}
if(input.charAt(i)=='m'||input.charAt(i)=='M'){
ints[12]++;
}
if(input.charAt(i)=='n'||input.charAt(i)=='N'){
ints[13]++;
}
if(input.charAt(i)=='o'||input.charAt(i)=='O'){
ints[14]++;
}
if(input.charAt(i)=='p'||input.charAt(i)=='P'){
ints[15]++;
}
if(input.charAt(i)=='q'||input.charAt(i)=='Q'){
ints[16]++;
}
if(input.charAt(i)=='r'||input.charAt(i)=='R'){
ints[17]++;
}
if(input.charAt(i)=='s'||input.charAt(i)=='S'){
ints[18]++;
}
if(input.charAt(i)=='T'||input.charAt(i)=='t'){
ints[19]++;
}
if(input.charAt(i)=='U'||input.charAt(i)=='u'){
ints[20]++;
}
if(input.charAt(i)=='V'||input.charAt(i)=='v'){
ints[21]++;
}
if(input.charAt(i)=='W'||input.charAt(i)=='w'){
ints[22]++;
}
if(input.charAt(i)=='x'||input.charAt(i)=='X'){
ints[23]++;
}
if(input.charAt(i)=='y'||input.charAt(i)=='Y'){
ints[24]++;
}
if(input.charAt(i)=='z'||input.charAt(i)=='Z'){
ints[25]++;
}
}
return ints;
}
}
but that's unrealistic approach to the problem.
so i want to know how to shorten the codes inside the for loop and how should i solve the part with special character.
Use the numeric representation of the char value to simplify. Google for any ASCII table to find these values.
a-z (lowercase) is 97 - 122.
So first convert the string to all lowercase then, for example:
if(charVal >= 97 && charVal <= 122){
ints[charVal - 97]++;
// The -97 gives you an array index of 0 through 25.
}
else {
// Otherwise it's not a-z.
ints[26]++;
}
Since this is clearly an homework, it would not be helpful for anyone to give you a silver plated answer. But here are some insight on how to optimize.
In Java, a character may be a numeric value. For instance str.charAt(0) - 'a' will return a numeric value, where 0 is a and 25 is z. (Note: there is a difference between "a" and 'a'; one is a String, the other is a char.) You'll also want to str.toLowerCase() your string, as 'a' != 'A'.)
Then, all you need to do is loop through all the characters of the string, get the character value (i.g. the array index) and increment your array. If the character value is less than 0 or greater than 25, then your character value is 26.
Hint: for (char c : input.toCharArray()) { ... }

java remove punctuation recursive method

I made a method to remove some punctuation from a String but its just returning the word passed in the parameter w/ the punctuation included, can anyone spot what's wrong?
public static String removePunctuation(String word) {
if (word.charAt(0) >= 32 && word.charAt(0) <= 46) {
if(word.length() == 1){
return "";
} else {
return removePunctuation(word.substring(1));
}
} else {
if(word.length() == 1){
return "" + word.charAt(0);
} else {
return word.charAt(0) + removePunctuation(word.substring(1));
}
}
}//end method
I ran the code you provided with the input:
h.ello and got the output hello
I am seeing a fully functional method here. I presume the punctuation you are trying to remove is not part of the ASCII range you provided in the if statement. Check your ASCII values against a chart.
ASCII values chart to compare with
Without including the proper values the input:
h[ello will return the output h[ello because the [ is ASCII value 91, which is outside the range you provided:
>= 32 && <= 46
There is nothing wrong with your algorithm. Most likely your range (32-46) doesn't include all the punctuation you're trying to remove. For example, ? is 63, so it will not get removed.

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.

Categories