简体   繁体   中英

How to print string from an int method without returning int?

I am working on a method. It returns int .

int top() {
   return q.peek();
}

The method above works fine for non-empty queue. It is not for empty queue.

When I modify this code to handle empty queue, it will be like this

int top() {
   if (q.isEmpty()) {
      System.out.println("queue is empty"); // I want to end the process here 
      return -1; // I don't want this line to return -1
   }
   return q.peek(); // I don't want this line to execute
}

System.out.println(q.top());

The result will be like this if the queue is empty

queue is empty
-1

I want it to print only queue is empty , not -1.

So is there a way to modify only top() method for this case in Java?

If you are able to change System.out.println(q.top()); to a call to only q.top(); you can simply just print from inside the method:

int top() {
   if (q.isEmpty()) {
      System.out.println("queue is empty");
      return -1;
   }
   System.out.println(q.peek());
   return q.peek();
}

If you are unable to change ANYTHING about the System.out.println(q.top()) statement you would need to return a String instead and use Integer.toString to convert the value to a String :

String top() {
    if (q.isEmpty()) {
        return "queue is empty";
    }
    return Integer.toString(q.peek());
}

Are you wanting to print the int returned only if the queue is not empty, otherwise print "queue is empty"? If so, how about doing something like this:

int top() {
  if (q.isEmpty()) {
    return -1;
  }
  return q.peek();
}

System.out.println(q.top() == -1 ? "queue is empty" : q.top());

And another option:

int top() throws Exception {
  if (q.isEmpty()) {
    throw new Exception("queue is empty");
  }
  return q.peek();
}

try {
  System.out.println(q.top());
} catch (Exception e) {
  System.out.println(e.getMessage());
}

When a method signature return int , you should not try to return another type as it can confuse other members who read your code.

If you cannot modify the System.out.println() method, the best option is to throw an Exception in your method like the answer given by Caitlyn Wiley.

Another acceptable way is to return an int that signify error (like you did with -1), as long as you have good docs to explain it.

I've just found another way to solve this problem without changing top() data type.

int top() {
    if (q.isEmpty())
        System.out.println("queue is empty");
        System.exit(0);
    return q.peek();
}

What do you guys think?

I thank you every answer to my question. I am very grateful. All answers are very useful.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM