I need to check if an element of a java array of characters is empty. I tried out the following code but didn't work. What's wrong?
char c[] = new char[3];
c[0] = 'd';
for (int i = 0; i < c.length; i++) {
if(c[i] == null) {
System.out.println(i + " is empty");
}
}
Let's take arrays out of the equation - an array is just a collection of variables, really. Let's consider a single variable. Suppose we had a method like this:
public boolean isEmpty(char c)
What would that do? The value of c cannot be null, because char is a primitive type. It could be U+0000 (aka '\u0000' or '\0' as character literals in Java), and that's the default value of char (for array elements and fields) but it's not the same as a null reference.
If you want a type which is like char but is a reference type, you should consider using Character - the wrapper type for char just like Integer is for int. Or if you know that you'll never use U+0000 as a valid value, you could just stick with that.
However, a better alternative would often be to design your code so that you don't need the concept of "empty or not empty". We don't know what you're trying to achieve here, but it's usually a good thing to at least consider. For arrays, the alternative is often to use an ArrayList<E> - but of course you can't have an ArrayList<char> in Java as Java generics don't allow primitive type arguments :(
An element of a primitive array can't be null. It will always have a default value if you didn't initialize it yourself. The default for char is 0.
Use Character class instead primitive char.
Character c[] = new Character[3];
c[0] = 'd';
for(int i = 0; i < c.length; i++){
if(c[i] == null){
System.out.println(i + " is empty");
}
}
You cannot use null as char is a primitive type. null only works for objects. use \0 as it's the primitive version of null.
primitive char's default value is 0. you can check it with 0
char c[] = new char[3];
c[0] = 'd';
for(int i = 0; i < c.length; i++){
if(c[i] == 0){
System.out.println(i + " is empty");
}
}
even, char=0 is also a character
Is your code compiling?
You should be seeing an error message at this code line if(c[i] == null)
And from error message, compiler is clearly revealing that "the operator == is undefined for argument type(s) char,null".
This should suffice that element of a primitive array (character array in this case)can't be null.
Replace null with '\0' with the quotes
Related
I am getting the "Must be an array type but it resolved to string" error in my code. It also says that i (in the code below) cannot be resolved to a variable which I don't get.
public class DNAcgcount{
public double ratio(String dna){
int count=0;
for (int i=0;i<dna.length();i++);
if (dna[i]== "c"){
count+= 1;
if (dna[i]=="g"){
count+=1;
double answer = count/dna.length();
return answer;
}
}
}
}
Could you guys please help me figure out where the problem lies? I'm new to coding in Java so I am not entirely comfortable with the format yet.
Thanks a lot,
Junaid
You cannot access a String's character using subscript (dna[i]). Use charAt instead:
dna.charAt(i) == 'c'
Also, "c" is a String, 'c' is a char.
One more thing - integer division ( e.g. int_a / int_b ) results in an int, and so you lose accuracy, instead - cast one of the ints to double:
double answer = count/(double)dna.length();
Use {} to define the scope of the loop. Also, as others already pointed out, use charAt instead of [] and use ' for characters, and use floating point division for the ratio.
for (int i = 0; i < dna.length(); i++) {
if (dna.charAt(i) == 'c') {
count += 1;
}
if (dna.charAt(i) == 'g') {
count += 1;
}
}
Or a bit shorter, use || to or the two clauses together
if (dna.charAt(i) == 'c' || dna.charAt(i) == 'g') {
count += 1;
}
I think you are currently a bit weak at brackets , this is what i understood from your code and corrected it;
public class DNAcgcount{
public double ratio(String dna){
int count=0;
for (int i=0;i<dna.length();i++){
if (dna.charAt(i)== 'c')
count+= 1;
if (dna.charAt(i)=='g')
count+=1;
}
double answer = count/(double)dna.length();
return answer;
}
}
After if we have to close the brackets when what you want in if is finished . I think you wanted count to be the number of time c or g is present in the dna.
You also did some other mistakes like you have to use 'c' and 'g' instead of "c" and "g" if you are using .charAt(i) because it will be treated like a character and then only you can compare .
You may view this link
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
and you may also have a look at works you can do with string like charAt.
It seems like that you have a few problems with the main syntax of basic java functions like loops or if-else statement. Click here for a good tutorial on these.
You must correct your for-loop and your if-statement:
for(int i=0;i<dna.length();i++){
if(...){
...;
}
if(...){
...;
}
}
Now you wont get the Cant be resolved to a variable... exception.
Second thing is the usage of your string. You have to use it like this:
for(int i=0;i<dna.length();i++){
if(dna.charAt(i) == 'c'){
count += 1;
}
if(dna.charAt(i) == 'g'){
count += 1;
}
}
Now all your exceptions should be eleminated.
Your problem is with syntax dna[i], dna is a string and you access it as it would be an array by []. Use dna.charAt(i); instead.
You using String incorrectly. Instead of accessing via [] use dna.charAt(i).
Altough logically a string is an array of characters in Java a String type is a class (which means it has attributes and methods) and not a typical array.
And if you want to compare a single character to another enclose it with '' instead of "":
if (dna.charAt(i) == 'c')
.
.
There are two errors:
count should be double or should be casted do double answer = (double)count / dna.length();
and as mentioned above you should replace dna[i] with dna.charAt(i)
I have this small part of a code. When I compare array a[j] != 42, it works like a charm. But if I tweak it to a[j] = 42 , it says:
cannot convert from 'int' to 'boolean'
What wrong I am doing?
for(int i = 0; i <= 9; i++) {
a[i] = Integer.parseInt(br.readLine());
int j = 0;
do {
if (a[j] = 42)
System.out.println(a[j]);
else {
flag=0;break;
}
j++;
} while (flag == 1);
}
a[j]!=42 is a comparison. a[j]=42 on the other hand, is an assignment of the value.
The correct way to compare them is: a[j] == 42
As the other answers already mention a[j]=42 is an assignment. What you want it to compare two values. I want to include a little bit more information to what exactly is going on here.
Explanation: What your code does is assign 42 to a[j]. a[j] would be contain / be equal to 42 after that line. The assignment itself is fine.
But the compiler expects a boolean expression inside its if (...) to determine wether it should enter the following code block or the one of the else-branch. The assignment operator = in Java returns the assigned value. Therefore the statement a[j]=42 returns 42 which the compiler then wants to get a boolean value from, which it cannot since it cannot convert from int to boolean.
Solution: Use the == operator instead which does not assign at but compares the two values and returns a boolean wether or not the two are identical: if (a[j] == 42)
You must use == for comparing:
if (a[j] == 42)
if(a[j]=42)
This is equivalent to:
a[j] = 42
if(a[j]) {
}
Now, since you are checking 42 as boolean, you get the error: cannot covert from 'int' to 'boolean'
As other answers suggest, you need == for comparison.
This is my code
public static String change(String word, char gone, char here) {
char[] chars = word.toCharArray();
for (char c : chars) {
if (c == gone) {
c = here;
}
}
return new String(chars);
}
and this how i call it:
System.out.println(change("supper", 'p', 'o'));
the result is supper I was trying to find explanation to what is going on ...
the chars variable is a variable that is refers to an array object, and which contains the characters of the String object word. then the only explanation that I thought about is that in the for statement, java actually copies the chars array.Is that correct?
some users said that there is a warning in my code,
but here you go, no warnings
c = here;
Updates the value of the character, not the array. If you used an editor it would tell you that the assigned value is not used.
Editors like IntelliJ above are free, so you have no excuse.
The c variable is just a copied reference to the array element.
The reason for this is that the enhanced for loop uses an Iterator and in order to get the next element, it invokes the Iterator.next() method, which gives a copy to the original collection element.
In order to make it work, you have to directly set the new value into the array:
public static String change(String word, char gone, char here) {
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == gone) {
chars[i] = here;
}
}
return new String(chars);
}
In for loop u had checked whether gone to chars each character and changed value but that changed variable not used to change the again "chars". you had changed value of variable c every time but never used so u got "Supper" as it is. so if u want to change "Supper" then use following code
public static String change(String word, char gone, char here) {
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == gone) {
chars[i] = here;
}
}
return new String(chars);
}
What you did there is just change the local variable c not the element in the char array
It's not working because
for (char c : chars)
here you are creating a new variable c which contains a COPY of the character you are currently iterating over.
What you could do instead is using a c-style for loop, iterate over each array element and replace the element within the array, something like:
for (int i = 0; i < chars.length; i++) {
if (char[i] == gone) {
char[i] == here;
}
}
Or even better: Skip the loop and use Strings replace method.
No, java does not COPYing object in For loop, but you are not using object in this example. "char" is primitive variable so you always receive a copy of a primitive veriable.
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 have to write a program to input a String str and change the upper case to lower case and vice versa. For example:
input:
"abCD"
output:
"ABcd"
this is what I've got:
l-is the length of the string
for(int b=0;b < l;b++)
{
char let=str.charAt(b);
if(let>97 && let<122)
{char nlet=let-32;
System.out.print(nlet);
}
else if(let>65 && let<90)
{ char t=let+32;
System.out.print(t);
}
}
break;
}
the error coming for this line:"char nlet=let-32;" is:
required:char;found:int;
how do i fix this?
The issue is that 32 is an integer, and let is a char. Java will implicity convert the let value to an int when it encounters let-32 and the result is the int value (for 'a') 96 or whatever.
You need to cast the result back to char:
(char)(let+32)
Try to use the below updated for loop:
for(int b=0;b < l;b++)
{
char let=str.charAt(b);
if (Character.isLowerCase(let))
{
char nlet=Character.toUpperCase(let);
System.out.print(nlet);
} else if(Character.isUpperCase(let))
{ char t=Character.toLowerCase(let);
System.out.print(t);
}
}
break;
}
Without any other classes (like Character for apparently you can't use it), you need to cast into char :
for(int b=0;b < l;b++)
{
char let=str.charAt(b);
if(let>97 && let<122)
{
char nlet=(char) let-32;
System.out.print(nlet);
}
else if(let>65 && let<90)
{
char t=(char)let+32;
System.out.print(t);
}
}
Your compiler told you the answer here :
required:char;found:int
It means your operation, here it is variable assignation has a wrong argument.
When you have
char nlet = xxx
The compiler expects the xxx to be castable into char. Here you give it a int value with let-32 or let+32.
So here you need to cast into char or use a function that output a char from an int; that's where you see all the people here telling you to use Character class that gives you all helper functions to do your homework (which is also way better than manually add/sub 32)
Careful, sometime you can see something like String str = "A string from int: " + 2000
This means your compiler will automatically cast the 2000 into "2000" because the + operation for a String takes 2 string arguments.
The Problem is with your let-32; it will return an integer so you need to implicitly cast it to a char variable.
Change your code to char nlet=(char) (let-32);
Also there is one more problem in your if condition you program will not give the correct output as your are not checking for the alphabets 'a' and 'z'.Change your if -else to check for the boundary conditions.
if(let>=97 && let<=122)
{
}else (let>=65 && let<=90){
}