Understanding Java methods - java

So, I'm very new to Java, I have a summer college course and we're on functions or methods and I'm having a bit of trouble understanding them.
There is a question on a lab I'm having a little trouble with:
"Write a method called MaxOfThree that accepts three integer
parameters and returns the largest of the three."
This is what I have so far but I'm not sure whats wrong. I added the print statement at the end because I wasn't getting a return value when I ran it but now I'm getting errors and it's not compiling. If you could help me understand methods a bit more I'd greatly appreciate it. For instance how the parameters work and calling it and if what's included in the function call is correct and how that works. I just get so confused when I read through the material and was hoping for an explanation in more layman's terms. Thanks for any help, here is what I have so far.
public class Test {
public static void main(String[] args) {
int a = 2, b = 3, c = 4;
int maxValue = max3(a, b, c);
}
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
System.out.println(max);
}
}
Here are the errors I'm receiving just in case...
Test.java:16: error: unreachable statement
System.out.println(max);
^
Test.java:17: error: missing return statement
}
^
2 errors

You can't have a statement after the return statement, or to be more exact - a statement imediatelly after a return statement (such as your println) can never be executed, and is therefore an error.
The println should be before the return statement.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}

I suggest You to change those if statements into one simple for loop with simple int[] vector. This solution is much more elegant and flexible. Additionally, You initialized and not used anywhere int maxValue = max3(a, b, c); in Your code.
public class Demo {
public static void main(String args[]) {
int[] numbers = new int[] {2, 3, 4};
System.out.println(maxValue(numbers));
}
public static int maxValue(int[] n) {
int max = n[0];
for (int i = 1; i < n.length; i++) {
if (n[i] > max) {
max = n[i];
}
}
return max;
}
}
But let's bow for a moment on the problem of methods implementation in Java.
At the begining of Your journey through the vastness of the Java realm You should get familiar with two types of methods: 1) void methods, and 2) return methods. The first ones are responsible for doing something without returning any value. We can for example use them for setting values of the fields of our application, initializing GUI, or other operations. The use of the void method can look like this:
/* method declaration */
void setValue(int value) {
someField = value;
}
/* method invocation */
setValue(5);
After invocation of setValue(5) the value of the someField object will be 5. However, you have to remember about type compatibility, so in this case someField can not be e.g of String type.
Second method type mentioned above, i.e return method is very useful, when you expect the method to give You an output, e.g in result of some operations conducted on the data You've given to Your method. But of course it's not necessary, to provide for the return method an input. Anyway, the use of return method can look like this:
/* method returns text You've given to it */
String getText(String text) {
return text;
}
/* method returns result of addition of three given int's */
int calculate(int a, int b, int c) {
return a + b + c;
}
/* method return a random number */
int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
You can easily see, that there is plenty of space for improvisation. Basicaly and in summary, void methods can work with given objects, for example can set values and conduct other operations, but thay don't return any STRAIGHT results You can work with. Return methods, from the other hand, provide You physical results, which You can use in further operations, or even in other methods, for example:
import java.util.Random;
public class Demo {
private static int someValue;
public static void main(String args[]) {
setValue(calculate(
createRandomNumber(),
createRandomNumber(),
createRandomNumber()));
System.out.println(someValue);
}
public static void setValue(int value) {
someValue = value;
}
public static int calculate(int a, int b, int c) {
return a + b + c;
}
public static int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
}

The problem is that the compiler detects that execution will never reach the System.out.println line, so it refuses to compile. The line return max; effectively ends the method, so nothing more will run after that.
You should move return max; to below the System.out.println line.

Swap your last 2 lines (return and System).

It should be like this, return max statement should be the last line in your method if you want to print something, because return statement goes back or invoke the line that called him,so your print statement is not reach.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}

You need to put
System.out.println(max);
before:
return max;
the reason is your return unconditionally ends the function and therefore the compiler won't reach the println causing a compile error.

You have a System.out.println() statement after the return. return ends the method and so the System.out.println() will never happen because the method will have ended. That's why you are getting errors. Put the System.out.println() before the return:
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}

As already been said, after you return something, the method will end. So your output in the last line of the method will not be executed, so remove it.
You can print the returned value of the method when you write the following outside of the method:
System.out.println("highest value:" + max3(a,b,c));
So now, the 3 values are given to the method which can do something with them now. After it did the calculations, the method returns a value, which can now be printed to the console for example.

The issue with the code you provided is that you're trying to print to the console, after you use your return statement. This causes your program to never reach that line: System.out.println(max);

Related

return statement does not ending method java

public class Interpolation_search {
public static void main(String...s) {
int rr[]= {1,2,3,4,9,10,15,80};
System.out.println(search(rr,0,7,3));
}
static int search(int ar[], int lo, int hi,int X) {
if(lo<hi&&ar[lo]!=ar[hi]) {
int mid=lo + ((hi-lo)/(ar[hi]-ar[lo]))*(X-ar[lo]);
if(X==ar[mid])
return 1; //l1
else if(X>ar[mid])
search(ar,mid+1,hi,X);
else search(ar,lo,mid-1,X);
}
return 0; //l2
}
}
return is executing twice first at l1 and second at l2.
It seems that you have difficulties understanding recursion.
Your method search() is supposed to return an int result. And the method itself calls itself (using different arguments) repeatedly. Thing is: you are all ignoring these recursive calls.
In other words: the real answer is for you to step back and understand what recursion is meant to be, and how to properly use it. As a starter, you could try to change
search(ar,mid+1,hi,X);
to
return search(ar,mid+1,hi,X);

Java, why is Math.sqrt() returning 0

I'm trying to check if a number is a square, and if a number is triangular.
The issue is happening at sqrt(num) which is returning 0 for all numbers I test.
I'm using an online compiler, tried several compilers, so it's not a compiling issue. Tried to declare num as a double and as an int, same results.
I'm new to Java, but not new to programming, I searched online, checked my code several times, everything looks fine, it even worked as expected before adding the variables for checking triangular number, but after declaring the variables checkTri and checkTriSqr, this started to happen. I'm sure this have nothing to do with declaring these variables (almost sure), could anyone please help me understand what's going on here?
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Parent{
public static void main(String[] args){
class Number
{
public int num ;
double numSqr = sqrt(num );
double roundNumSqr = round(numSqr) ;
double checkTri = 8 * num + 1 ;
double checkTriSqr = sqrt(checkTri) ;
public void prinTest()
{
System.out.println(num);
System.out.println(numSqr);
System.out.println(roundNumSqr);
System.out.println(checkTri);
System.out.println(checkTriSqr);
}
public boolean isSqr()
{
if (numSqr == roundNumSqr)
{
return true;
}
else
{
return false;
}
}
public boolean isTriangular(){
if (checkTriSqr * checkTriSqr == checkTri )
{
return true;
}
else
{
return false;
}
}
}
Number number = new Number();
number.num = 350;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
EDIT: The following screen shot is from the tutorial I'm following, concerning declaring classes within methods!
This:
public int num ;
double numSqr = sqrt(num );
initialises num to 0 upon instance construction (the default value for an integer in the absence of assignment), and numSqr is set immediately afterwards (to zero).
You need to recalculate the sqrt() each time you subsequntly set num (perhaps by providing a method setNum() and recalculating everything within that method)
I wouldn't call your class Number, btw. There's already a Number class in the standard Java class set.
numSqr is created in the constructor, whereas number.num = 350;is declared after the construction of your object.
You can use a constructor like this :
public Numer(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
You can also use an empty constructor and a setter to set the number attribute :
public void setNumber(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
The values numSqr, roundNumSqr, etc, are all set at the point of the object's creation, however you don't set num to anything until after the object is created. The result is that, for instance,
At creation:
num = 0
therefore
numSqr = 0
roundNumSqr = 0
etc
Then, you set num = 350
But you don't reset the values of numSqr, etc, so this is still the case:
numSqr = 0
roundNumSqr = 0
You need to make a constructor for this class that takes in the value of num and then sets all of the corresponding values, so that they're only set after num has been set (or, add a "calculate" function that updates all the values).
You can modify in this way and compare with technology you have worked on .
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Number {
public int num = 0;
public void prinTest() {
System.out.println(this.num);
System.out.println(this.getSqrt(this.num));
System.out.println(this.getCheckTri());
}
private double getSqrt(double value) {
return sqrt(value);
}
public boolean isSqr() {
if (this.getSqrt(this.num) == round(this.getSqrt(this.num))) {
return true;
} else {
return false;
}
}
private double getCheckTri() {
return 8 * this.num + 1;
}
public boolean isTriangular() {
if (this.getSqrt(this.getCheckTri()) * this.getSqrt(this.getCheckTri()) == this.getCheckTri()) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Number number = new Number();
number.num = 49;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
You should read some basic tutorials as you have added class inside main method,which means you need more time to check out the syntax.
The other answers alreade said, that the field num was not set to the input number, and that the other fields were actually evaluated on object creation, and hence zero too.
The purpose however is achieved by simple functions:
public static boolean isSquare(int num) {
int root = (int) Math.round(Math.sqrt(num));
return root*root == num;
}
public static boolean isCubic(int num) {
int root = (int) Math.round(Math.cbrt(num));
return root*root*root == num;
}
This exploits the cubic root.
As a comparison of doubles, a sqrt result and its rounded long value are still imprecise, I prefer to recalculate the original parameter.
public int num ;
double numSqr = sqrt(num);
By default, declared instance integer variables (variables declared inside class body) are initialized with 0 (zero). Hence, your code does nothing but take a square root of zero, which is zero.

How does return value work in java methods

I made this code to learn my self about how return works in java
public class test {
public int sumDouble(int a, int b) {
int k = (a + b);
if (a == b) {
k = k * 2;
} else {
k = (a + b);
}
return k;
}
public static void main(String[] args) {
System.out.println("Enter your number");
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
test t = new test();
t.sumDouble(a, b);
}
}
I want to use the return k to print out the value of summation
How can use the return k to print out the sum value?
I tried to write System.out.println(t.k); in the main method but it did not work ..
thanks
The thing to keep in mind here is that k is a local variable in the sumDouble method, so you can't refer to it elsewhere.
You can take the value returned by sumDouble and use it in your main method, however.
For instance, you can create a variable in main and assign its value to be the value that is returned from sumDouble, and you could print that variable, since it's in scope:
// at runtime, this will evaluate "t.sumDouble(a, b)"
// and assign the value that it returns to the variable "sum"
int sum = t.sumDouble(a, b);
System.out.println(sum);
You could even skip the local variable and use the method call directly:
System.out.println(t.sumDouble(a, b));

Use the Object that is calling the method

Apologies for the terribly worded question, but I'm a bit new to Java and still a bit unsure how to word my problems/ not really sure if it's possible to do what I want to.
I have a class called ClassA which has a trivial method returnInt that looks something like this:
public class ClassA {
private int numberino;
public ClassA(Int int) {
this.numberino = int;
public boolean isPositive(){
if (this.numberino > 0){
return true;
return false;
public int returnInt() {
final int addVal = 2;
int sum = 1
sum = addVal*numberino + sum;
return sum;
}
Now when I call this method in another main loop, like:
ClassA temp = new ClassA(7);
temp.returnInt();
My question is, is there anyway I can pass the object temp into the returnInt() method, so I could perhaps use the isPositive(int) method on it without changing the structure (by passing in an argument) of the returnInt() method?
Something like this is how I would imagine it being (but I know it's wrong);
public int returnInt() {
final int addVal = 2;
int sum = 1
if (temp.isPositive()){
sum = addVal*numberino + sum;
}
return sum;
Where that temp is Object being created and the method returnInt() is the method being used from it.
I hope that makes sense.
Thanks!
returnInt is an instance method of ClassA, so it can call any method of ClassA. There's no need to pass anything.
public int returnInt() {
final int addVal = 2;
int sum = 1
if (isPositive()) { // or this.isPositive() if you want to be explicit
sum = addVal*numberino + sum;
}
return sum;
}

Getting product and quotient of 2 numbers using recursion without using the * and / operators

I am trying to learn programming and I am on the phase of learning recursion. Before this, I have successfully solve the problem but using loops. Right now, since recursion is quite interesting to me, I was wondering if I could convert the loop into a recursive method. I have done my attempts but I've been getting a sort of infinite computation whatsoever.
Can somebody give me a hand with this? Thanks.
This is my code.
public class RecursiveProduct {
public static void main (String[] args) {
Scanner myInput = new Scanner(System.in);
System.out.print("Enter num1: ");
int num1 = myInput.nextInt();
System.out.print("Enter num2: ");
int num2 = myInput.nextInt();
int product = recursiveProduct(num1, num2);
System.out.print(num1 +" * " +num2 +" = " +product);
}
public static int recursiveProduct(int a, int b)
{
int result = 0;
if(b == 0)
return result;
else
{
result += a;
return result += recursiveProduct(a, b--);
}
}
}
First, this is C++ code, but I will explain Java code later:
int function(int a, int b, int &counter,int &result){
if(b==0 || a==0)
return 0;
if(counter==b)
return 1;
else{
result+=a;
counter++;
function(a,b,counter,result);
}
}
Function takes two references int &counter and int result. Unfortunately, you can't pass primitive types by reference in Java, so you should declare Wrapper class, and then call your method, something like this:
class MyInt{
public int value=0;
}
Here you will bi 100% sure that object of MyInt will be passed by value, but itself is reference so you get what you want. Reimplement our function:
void function(int a, int b, MyInt counter,MyInt result){
if(b==0 || a==0)
return 0;
if(counter==b)
return 1;
else{
result.value+=a;
counter.value++;
function(a,b,counter,result);
}
}
Call your method like this bellow, and everything should work:
int a=2,b=5;
MyInt counter=new MyInt();
MyInt result=new MyInt();
function(a,b,counter,result);
Try this:
public static int recursiveProduct(int a, int b) {
if (b == 0) {
return 0;
} else {
return a + recursiveProduct(a,--b);
}
}
You are almost there: just add result += recursiveProduct(a, b--); instead of just calling the function.
EDIT: call it with b- 1 not with b--
I suggest you simplify your code.
Something like
return b == 0 ? 0 : a + fn(a, b-1);

Categories