Skip to content
Advertisement

Returning an int array in Java

So I need a script that returns an array of a text document. The document is all numbers. Everytime I try to run it I get this message “This method must return a result of type int[]” this is under the checker part. I am trying to return it to another class so that I can use the array for if statements. Could anyone help me out with this?

JavaScript

Expected outcome is: {0, 40}

Advertisement

Answer

The compiler is complaining because it thinks there is a possible exit path which skips all the other return statements. What happens if hasNextLine returns false on the first interaction?

In this case, you should move the return in the catch clause to the end of the method

JavaScript

Have a look at The try-with-resources Statement for more information on what try (Scanner myReader = new Scanner(myObj)) { is doing

They numbers seperated by line breaks like so : 0 40 30

So, a better solution might look something like…

JavaScript

The problem with using an array of this, is the fact that you don’t know how many lines (or elements) there are, so, you need something more dynamic, like a List, which you can continuously add new elements to, without needing to know how many you need to store up front.

This is a little more “advanced”, but generally, I would consider using List over arrays in most cases, but that’s me and I’m lazy.

Expected outcome is: {0, 40}

If you only want a fixed number of elements, then count the number of lines you’ve read and exit early when you’ve reached it

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement