I am working on an exercises from Objects first with java for self review. The part of the exercises that I am having trouble with is where it asks me to find the length of the refNumber string..if the length of the string is zero, then print out a line saying "zzz". I have tried doing this by making a local variable, and making it equal to refNumber.length(). However in my conditional statement bluejay indicates that I have an incompatible type. Ugh, please help. Thanks in advance.
class Book
{
// The fields.
private String author;
private String title;
private int pages;
private String refNumber;
/**
* Set the author and title fields when this object
* is constructed.
*/
public Book(String bookAuthor, String bookTitle, int numberOfPages)
{
author = bookAuthor;
title = bookTitle;
numberOfPages = pages;
refNumber = "";
}
public String getAuthor()
{
return author;
}
public String getTitle()
{
return title;
}
public int getPages()
{
return pages;
}
public String getRefNumber()
{
return refNumber;
}
public void setRefNumber(String ref){
ref = refNumber;
}
public void printTitle() {
System.out.println("Book desciption: " + title);
}
public void printAuthor() {
System.out.print(" by " + author);
}
public void printPages(){
System.out.println("Pages: " + pages);
}
public void printRef(){
int count = refNumber.length();
if (count = 0){ //incompatible type wtf?
System.out.println("zzz");
}
else {
System.out.println("Reference Number: " + referenceNumber);
}
}
Most programming languages use the single equals sign =
to be an assignment operator. What you are trying to do is compare the two numbers, which uses the double equal sign ==
.
So, effectively, your code is trying to assign count with the value 0
, then check if the value is true
or false
. And since the result of an assignment operation is neither true
nor false
, it throws the error.
As other people are saying, use count == 0
.
try it ..get out put
if (refNumber.length() == 0){
System.out.println("zzz");
}
Use this:
if (count == 0){
....
}
'=' is assignment operator and '==' is comparison operator
It should be
if(count == 0)
In your code it's like you are assigning 0 to count which cannot happen in the if clause, since it expects a boolean based on the condition. So here you should check if count is equals (using equality operator == ) and in return it returns true if they are equal or false otherwise.
count=0
代表赋值,而count==0
代表比较。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.