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.
Related
set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());
I encountered this code from written by someone. It is java code.
s is a char[].
set is a String set.
So why does he use String and then StringBuffer?
String has a constructor which takes an array of chars, hence why they create a new String first.
Then to reverse the String, they create a StringBuffer to use a built in reverse function in order to not implement their own. StringBuffer's constructor takes a String, hence why a String is made first and then a StringBuffer
Let's split the 3 parts on 3 lines to compare:
set.add(
new String(s)
+ (ch == 0 ? "" : ch)
+ new StringBuffer(new String(s)).reverse()
);
Rewritten
It is equivalent with
String trimZero = ch == 0 ? "" : String.valueOf(ch);
set.add(String.valueOf(s) + trimZero + StringUtils.reverse(s));
Well, using Apache's StringUtils.reverse().
If s is a String it can simply added as is, for example, in an alternative way (to emphasize the different structures):
if (ch == 0) {
set.add(s + StringUtils.reverse(s));
} else {
set.add(s + String.valueOf(ch) + StringUtils.reverse(s));
}
Output wise
For example:
alphabet gets added as alphabet8tebahpla (for coincidence ch is a non-zero integer).
an gets added as anna (given that ch == 0)
Abbreviations and naming-conventions
When guessing the types I would say:
ch probably is a primitive char, array of that, or CharSequece
s most-likely is a String (rather than the rarely used short integer)
Usually abbreviations in symbols/names are ambiguous and can be considered a code-smell.
However there seems to be a historical and accepted convention or habit, especially for temporary / looping variables like:
int i
String s
char ch
The Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori, Chapter 1. Naming Conventions assorted them in a table:
Temporary variable names may be single letters such as i, j, k, m, and n for integers and c, d, and e for characters. Temporary and looping variables may be one-character names as shown in Table 1-1.
Even core Java methods have such (ambiguous) abbreviated parameter-names
if the method-context is obvious enough
that the contents and purpose of the parameter is self-explaining
E.g. String.contains(CharSequence s)
The constructor will throw an IllegalArgumentException exception with the message "Invalid Address Argument" if any parameter is null, or if the zip code has characters others than digits.
The method Character.isDigit can help during the implementation of this method. See the Java API (Character class) for additional information.
I've had the illegal argument exception down. But, not the zip code. Help?
Program.
if(street==null||city==null||state==null){
throw new IllegalArgumentException("Invalid Address Argument");
}
if(zip == Character.isDigit(ch)){
//To do???
}
try apache stringutils
public static boolean isNumeric(CharSequence cs)
Checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false.
null will return false. An empty CharSequence (length()=0) will return false.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = false
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
cs - the CharSequence to check, may be null
Returns:
true if only contains digits, and is non-null
Since:
3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence), 3.0 Changed "" to return false and not true
int zipcode = 0;
try {
zipcode = Integer.parseInt(zipcode);
}catch (Exception e){}
if (zipcode <= 0)
{
throw new Exception(..);
}
And less than 1,000,000 if you want to be precise. You are using Char which makes no sense as you will have a String.
This sounds like homework to me, so I think the first thing you need to do here is learn how to read the documentation. Let's start by taking your instructor's hint, and looking up the documentation for Character.isDigit(char ch)
public static boolean isDigit(char ch)
Handwaving away some of the terms there, the critical things are that the method is static (which means we call it like Character.isDigit(myVariable) and that it returns a boolean (true or false value), and that it accepts a parameter of type char.
So, to call this method, we need a char (single character). I'm assuming that your zip variable is a String. We know that a string is made up of multiple characters. So what we need is a way to get those characters, one at a time, from the String. You can find the documentation for the String class here.
There's a couple of ways to go about it. We could get the characters in an array using toCharArray(), or get a specific character out of the string using charAt(int index)
However you want to tackle it, you need to do this (in pseudocode)
for each char ch in zip
if ch is not a digit
throw new IllegalArgumentException("Invalid Address Argument")
I must compare if a char is null. I think about that (char is the name of my variable):
Character.toString(sauv).equals(null)
OR
Character.toString(sauv) == null
OR
char.equals(null)
OR
char == null
But it didn't work. How could I compare char with null?
I checked my method with a char table with size 4 and with 3 elements in the table. For example: {1,2,3, }
My method must check that I changed a char in this table, otherwise that null. The changed character must be returned.
char cannot be null.
try using '\0'. this might help yu
I'm converting a C prog that parses a text string and produces human readable o/p.
Got it nearly done, but having a problem understanding the difference in
*char_ptr++
and
char_ptr-- in
token[i++] = c = toupper(*char_ptr++);
if (c == '\0')
{
char_ptr--;
return( 0 );
}
Am I correct in thinking that *char_ptr++ will effectivley point to the next char in the 'string'?
If so, what does char_ptr-- do?
Thanks.
Regard *char_ptr++ as:
char tmp = *char_ptr;
char_ptr++;
c = toupper(tmp);
So it effectively fetches the current character, and advances the pointer by one. Because the ++ operator has a higher precedence than the unary *, such an expression is evaluated in the order *(char_ptr++).
The incrementation is applied first, but since the postfix ++ operator returns the result prior to the manipulation, the * dereferencing operator is applied on the old address.
char_ptr-- simply decreases the pointer by one.
In the same way as ++ increments the pointer and points to the next character, -- decrements it, pointing to the previous character. In this case, it puts it back to the last real character from the terminating null.
Because you're converting to java, you're going to have to remove the pointers, Java doesn't support them.
token[i++] = c = toupper(*char_ptr++);
if (c == '\0')
{
char_ptr--;
return( 0 );
}
Likely had some sort of declaration above it saying:
char* char_ptr = some_array;
Instead, that'll be
int pos = 0;
And the above code becomes:
token[i++] = c = toupper(some_array[pos++]);
if (c == '\0')
{
pos--;
return( 0 );
}
Yes, you are correct. It's a way of "peeking" ahead into the "string" and then returning to where you were if the string was at it's end.
This question is solved by precedence rules. The expression
*char_ptr++
is resolved to
*(char_ptr++)
meaning "The character after the character that ptr is pointing to". So when c equals a '\0' (zero), the pointer gets decremented, so it points to the previous character. It practically decrements to the previous character whenever there's a 0 encountered, so that char_ptr points to whatever it pointed to during the last run of the block.
I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string.
The Javadocs only say this method returns the index in this string of the specified string, -1 if the string isn't found.
To me this behavior seems highly unexpected, I would have expected a -1. Any ideas why this unexpected behavior is going on? I would at the least think this is worth a note in the method's Javadocs...
System.out.println("FOO".indexOf("")); // outputs 0 wtf!!!
System.out.println("FOO".indexOf("bar")); // outputs -1 as expected
System.out.println("FOO".indexOf("F")); // outputs 0 as expected
System.out.println("".indexOf("")); // outputs 0 as expected, I think
The empty string is everywhere, and nowhere. It is within all strings at all times, permeating the essence of their being, yet as you seek it you shall never catch a glimpse.
How many empty strings can you fit at the beginning of a string? Mu
The student said to the teacher,
Teacher, I believe that I have found the nature of the empty string. The empty string is like a particle of dust, and it floats freely through a string as dust floats freely through the room, glistening in a beam of sunlight.
The teacher responded to the student,
Hmm. A fine notion. Now tell me, where is the dust, and where is the sunlight?
The teacher struck the student with a strap and instructed him to continue his meditation.
Well, if it helps, you can think of "FOO" as "" + "FOO".
int number_of_empty_strings_in_string_named_text = text.length() + 1
All characters are separated by an empty String. Additionally empty String is present at the beginning and at the end.
By using the expression "", you are actually referring to a null string. A null string is an ethereal tag placed on something that exists only to show that there is a lack of anything at this location.
So, by saying "".indexOf( "" ), you are really asking the interpreter:
Where does a string value of null exist in my null string?
It returns a zero, since the null is at the beginning of the non-existent null string.
To add anything to the string would now make it a non-null string... null can be thought of as the absence of everything, even nothing.
Using an algebraic approach, "" is the neutral element of string concatenation: x + "" == x and "" + x == x (although + is non commutative here).
Then it must also be:
x.indexOf ( y ) == i and i != -1
<==> x.substring ( 0, i ) + y + x.substring ( i + y.length () ) == x
when y = "", this holds if i == 0 and x.substring ( 0, 0 ) == "".
I didn't design Java, but I guess mathematicians participated in it...
if we look inside of String implementation for a method "foo".indexOf(""), we arrive at this method:
public int indexOf(String str) {
byte coder = coder();
if (coder == str.coder()) {
return isLatin1() ? StringLatin1.indexOf(value, str.value)
: StringUTF16.indexOf(value, str.value);
}
if (coder == LATIN1) { // str.coder == UTF16
return -1;
}
return StringUTF16.indexOfLatin1(value, str.value);
}
If we look inside of any of the called indexOf(value, str.value) methods we find a condition that says:
if the second parameter (string we are searching for) length is 0 return 0:
public static int indexOf(byte[] value, byte[] str) {
if (str.length == 0) {
return 0;
}
...
This is just defensive coding for an edge case, and it is necessary because in the next method that is called to do actual searching by comparing bytes of the string (string is a byte array) it would otherwise have resulted in an ArrayIndexOutOfBounds exception:
public static int indexOf(byte[] value, int valueCount, byte[] str, int strCount, int fromIndex) {
byte first = str[0];
...
This question is actually two questions:
Why should a string contain the empty string?
Why should the empty string be found specifically at index zero?
Answering #1:
A string contains the empty string in order to be in accordance with Set Theory, according to which:
The empty set is a subset of every set including itself.
This also means that even the empty string contains the empty string, and the following statement proves it:
assert "".indexOf( "" ) == 0;
I am not sure why mathematicians have decided that it should be so, but I am pretty sure they have their reasons, and it appears that these reasons can be explained in layman's terms, as various youtube videos seem to do, (for example, https://www.youtube.com/watch?v=1nBKadtFViM) although I have not actually viewed any of those videos, because #AintNoBodyGotNoTimeFoDat.
Answering #2:
The empty string can be found specifically at index zero of any string, because why not? In other words, if not at index zero, then at which index? Index zero is as good as any other index, and index zero is guaranteed to be a valid index for all strings except for the trifling exception of the empty string.