Alternative to using return statement - java

I'm having trouble understanding what exactly the return statement does. What would be the difference in using:
public void run()
{
System.out.println(cube(5));
}
public int cube(int num)
{
int result = num*num*num;
System.out.println(result);
}
vs
public void run()
{
System.out.println(cube(5));
}
public int cube(int num)
{
return num*num*num;
}
Isn't it basically doing the same?

In your first example, the square function will print the cube of the provided number. However, if you wanted to do something more with it, like System.out.println(square(5) + 3), printing would not give you back 125 (did you mean to call it cube?) to add to the 3, it would only say "125" in the console. The return statement actually makes the function give back 125, so you can continue to work with it as a value.
Additionally, since you declared the square function as returning an int, if you do not have a return statement, then the program will fail to compile.

The return statement allows for more modular code with clear separation of concerns.
In your first example, your first System.out.println in the run() method calls another method that both calculates and then prints; therefore, the first System.out.println doesn't print anything itself, and could be simplified to just
public void run() {
square(5);
}
public void square(int num) {
System.out.println(num * num);
}
Which is nice and concise, but let's say you don't want to System.out.println every time you calculate a square, but only print if the result is divisible by 3. If you add the logic for that scenario to your square() method, it starts to exceed its responsibility. Additionally, your square() method is now only useful to that specific scenario. So the better practice would be something like this:
public void run() {
int result = square(5);
if (result % 3 == 0) {
System.out.println(result);
}
}
public int square(int num) {
return num * num;
}
Which now allows you to re-use the square() method for other scenarios, rather than just printing squares divisible by 3.
Unrelated to the code itself, but your square() method is actually calculating a cube (num*num*num) rather than a square (num*num)

The difference would be whether or not you want to do something with the product of the function. If you just want to print the result, you're good to go. If you want to store that value into a variable to use later, you'd want to return it, and you could then call a System.out.println on that variable too. I would say fin nailed it in his response. Hope this helped!

Related

Using random numbers in switch/case statement in java

wanted to use a switch statement in Java, but the variable in the switch-statement (switch(variable)) should be compared to random numbers in the case-statements (case(randomNumber)). But I get an error message like that: "case expressions must be constant expressions". So does my case-statements doesn't work with random numbers? I thought that the error message means that i have to preface the variables with "final", but that didn't work either. So, are if ... else statements the only way? I hope I explained my problem well enough to understand.
(I'm just beginning with java and the whole terminology that comes with coding)
int number = 6; //some number between 0-9
int randomNumber1 = ((int)(Math.random() * 10));
int randomNumber2 = ((int)(Math.random() * 10));
int randomNumber3 = ((int)(Math.random() * 10));
switch(number)
{
case(randomNumber1):
//some code here
case(randomNumber2):
//some code here
case(randomNumber3):
//some code here
default:
//some code here
}
The reason that it is not working is because you are doing
case(variable)
When I changed this to an actual number, it started working for me. It is saying constant expression required because it wants an actual number, not a number stored in a variable.
Hope this helps
As explained, the (expression) in a case (expression): statement must be a constant.
As for if-else being the only way, another possibility (depending on what you're trying to do overall) is to use the random numbers as keys in a map, with values of objects with a method that can be executed to perform the action you want.
Interface MyAction
{
public void doMyAction() {};
}
public class Eight implements MyAction
{
public void doMyAction() { System.out.println("I'm an eight"); }
}
public class Four implements MyAction
{
public void doMyAction() { System.out.println("I'm a four"); }
}
// ...
HashMap<Integer, MyAction> actionMap = new HashMap<>();
actionMap.put(8, new Eight());
actionMap.put(4, new Four());
// ...
MyAction myAction = actionMap.get(randomNumber);
if (myAction == null) { System.out.println("Don't have one of those"); }
else { myAction.doMyAction(); }
It's hard to see what overall goal you're trying to accomplish, which may be why you're not getting more response -- people here often don't like proposing something that may turn out to be 'wrong', even for a situation that wasn't explained completely.
As seen from the error you are getting, switch can only be used with constant expressions. To achieve what you want, you can only use branching with if, else if, and else.
if(number == randomNumber1){
//some code here
} else if(number == randomNumber2){
//some code here
} else if(number == randomNumber3){
//some code here
} else {
//some code here
}

Recursive method works wrongly

Just wrote simple java code to print 1 - 100 using recursive method.
Below is the code snippet
public class Test
{
public static void main(String[] a)
{
printNumber(0);
}
public static void printNumber(int i)
{
if (i < 100)
{
System.out.println(i);
i = i + 1;
printNumber(i);
}
System.out.println(i);
}
}
but the code prints
0, 1, 2, ............100, 100, 99, ................1
So anyone please tell why it is printing 100,99,98.........1 and what went wrong?
EDIT
I tried the logic to print 1 - 100 in all combinations and works well for me but output should be 1 - 99(print from inside condition) and finally 100(print by last print) but output is 1 - 100 and 100 - 1.
so please tell me why 100 to 1 is printing in output.
kindly dont tell me logic because I already got result what i expected
Use this code it works because when you call printNumber (i) it call and move further. after 100 it will stop calling itself and programcounter return to previous called function thus it printing 100 to 0
public class Test
{
public static void main(String[] a)
{
printNumber(0);
}
public static void printNumber(int i)
{
if (i < 100)
{
System.out.println(i);
i = i + 1;
printNumber(i);
}return;
}
}
just remove the second print statement like this:
public static void printNumber(int i)
{
if(i<=100)
{
System.out.println(i);
i = i + 1;
printNumber(i);
}
}
The recursive works as it is supposed to do
Each time you call printNumber(i); you're going up in the call stack, whenever you stop calling it, in this case when 1 = 100, it'll unstack and finish the code inside printNumber(), in this case, the rest of the code (after the recursive call ) is another print.
Each of those stacked calls have a different value for i since java is pass by value :
When I say pass by value it means whenever caller has invoked the
callee the arguments(ie: the data to be passed to the other function)
is copied and placed in the formal parameters (callee's local
variables for receiving the input). Java makes data communications
from one function to other function only in a pass by value
environment.
So it calls the prinln with each of those values ( 100..1 ) note that it does not do the first ( 0 ) since it has been incremented to 1 .
Nothing went wrong. The frist system out prints the accessing value at the method.
So it print the value before invoke printNumber() then when
the i value reach 101 the 101th printNumber method ends and the thread come back to the method invked before. So the second System out print the value of i of the specific method.
public class Test
{
public static void main(String[] a)
{
printNumber(0);
}
public static void printNumber(int i)
{
if(i<=100)
{
System.out.println(i);
i+= 1;
printNumber(i);
}
}

How to use a recursive method that has a return type void in java?

So I understand how to use a recursive method that has some other return type other than void. Typically I would call the same method again in the same method( inside the recursive case), while decremented or increment some value in the call to reach the base case. Then at some point the base case is reached and the problem is solved, so it starts returning the value from every call. Along those lines.
BUT
What if the method has the return type void, so you can't call the method as it won't/can't return anything? I'm trying to write a sentence backwards, which I've solved both with a for loop and a resucrive method that can return a string value, but I'm not sure how to approach it if it's void which is what the assignment is asking for.
Edit: I should also mention the sentence can only be passed in the parameter
Thank you everyone for the information and the help!
Recursion doesn't work only with methods/functions that return values. Recursion means only that the method/function calls itself.
You must guarantee that there is at least one stop condition but this does not require the function to return a value. This is commonly achieved by incrementally changing one or more arguments that you pass each time the function recursively calls itself. When that/those arguments satisfy a certain condition your function no longer calls itself and all pending operations are solved.
I am not fully aware of the task you are trying to do but here is an example of a recursive function that writes a string backwards. I use PSEUDO-functions with names that hopefully are self-explanatory.
public void writeBackwards(String str) {
// This is the negation of the stop condition, so the stop condition
// is when the string is empty, in which case this function will do
// nothing:
if (!str.isEmpty()) {
char firstCharacter = str.getFirstCharacter();
str = str.removeFirstCharacter();
writeBackwards(str); // the recursive call
// The following operation will be pending, waiting for the
// recursive call to be resolved first:
writeCharacter(firstCharacter);
}
}
You can use any mutable Object as a parameter of the recursive function to store the result. For example, the backwards-sentence problem you mentioned could be written as:
public void stringReverse(String s, int index, StringBuilder sb) {
if (index < 0)
return;
sb.append(s.charAt(index));
stringReverse(s, index - 1, sb);
}
And called like this
StringBuilder sb = new StringBuilder();
stringReverse(mySentence, mySentence.length() - 1, sb);
Just like in C++ you can pass in pointers, here in Java you can simply pass in a class object to your function to hold the value generated from the recursive calls of the function. A simple example reflecting your question to compute fibonacci number is following.
public class ComputeFibonacci {
static class Fibonacci {
public int ith;
public int value;
Fibonacci(int a, int b) {
ith = a;
value = b;
}
}
private static void fibonacci(Fibonacci result) {
if (result.ith == 1 || result.ith == 2) {
result.value = 1;
} else {
Fibonacci left = new Fibonacci(result.ith - 1, 0);
Fibonacci right = new Fibonacci(result.ith - 2, 0);
fibonacci(left);
fibonacci(right);
result.value = left.value + right.value;
}
}
public static void main(String[] args) {
// Here we compute the 10th fibonacci number
Fibonacci f = new Fibonacci(10, 0);
fibonacci(f);
System.out.println("The result is " + f.value);
}
}
Good luck.

Am I returning the correct value from my method & am I writing it correctly?

I'll preface my question with the statement that I am very new to Java, so I apologise if my code is totally disgusting to read.
What I'm trying to do: I'm writing a program that takes two integers from the user, a low value and a high value, and sends both integers to two different methods. Method #1 has a simple for loop and should print out all of the numbers between the lowest number and the highest number that are multiples of 3 or 5, and Method #2 does the same except for numbers that are multiples of 3 or 5 it also checks if that number is also a multiple of 6 and, if so, it prints the number and an asterisk next to it.
What I'm having trouble with: I'm pretty stumped on what I need to return from my methods & how to return anything at all. This is the first time I've worked on a method properly (just moved up from "Hello World) and from what I can see I don't really need to return anything at all. All the code that I've put in my methods pretty much complete the program, so I thought maybe returning the integers I sent would be enough, apparently it's not. So, without further ado, here's my code.
The Error:
javac BonusQ.java
.\MethodOne.java:19: error: illegal start of type
return(int lowestRange, int highestRange);
^
.\MethodTwo.java:36: error: illegal start of type
return(int lowestRange, int highestRange);
^
The Main:
import java.util.Scanner;
public class BonusQ
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int lowestRange = 0;
int highestRange = 0;
System.out.println("Enter the lowest integer in your range");
lowestRange = scan.nextInt();
System.out.println("Enter the highest integer in your range");
highestRange = scan.nextInt();
MethodOne.NoAsterisk(lowestRange, highestRange);
MethodTwo.Asterisk(lowestRange, highestRange);
}
}
MethodOne:
public class MethodOne
{
public static int NoAsterisk(int lowestRange, int highestRange)
{
for(int i = lowestRange; i <= highestRange; i++)
{
if (i%5 == 0)
{
System.out.println(i);
}
else if (i%3 == 0)
{
System.out.println(i);
}
}
}
return(int lowestRange, int highestRange);
}
MethodTwo:
public class MethodTwo
{
public static int Asterisk(int lowestRange, int highestRange)
{
for(int i = lowestRange; i <= highestRange; i++)
{
if (i%5 == 0)
{
if (i%5 == 0 && i%6 == 0)
{
System.out.println(i + "*");
}
else
{
System.out.println(i);
}
}
else if (i%3 == 0)
{
if (i%3 == 0 && i%6 == 0)
{
System.out.println(i + "*");
}
else
{
System.out.println(i);
}
}
}
}
return(int lowestRange, int highestRange);
}
Sorry if the post is a bit beefy to read, I just find that adding my thoughts on the code might help you explain to me what's going wrong, seeing as you may not know the extent of my incompetence :)
Thanks in advance.
Ok, Classes have members.
Members are either some variables or arrays of variables
and the methods of a class.
So you got
public class MyMethod
{
public static int Asterisk(int loRange, int hiRange)
{
// Do magic let's make a sum for this example
// You enter loRange and hiRange (you defined it above)
return loRange + hiRange // Here the method returns a result
}
}
// So then....
public static void main(String [] args)
{
// WHATEVER IS IN HERE RUNS ALWAYS FIRST.
z = Asterisk(1,2); // 1 and 2 is lo and hi range values ;)
// Z has a value of 3 now because Asterisk(1,2) returns 1 + 2
}
See how this works?
Now this works because you use the static definition (meaning there must not be an instance of MyMethod created first to use the method. It's not wrong, but if you can make a program do things with class instances, you better do it that way.
You make an instance of a class, this is called an object, using a special method. This method has the exact name of the Class and constructs an instance of it.
You should study now about constructors, abstract classes etc etc.
I can't say you do it wrong or right either. It is about what the program is all about and you should study the scope for variables and methods, and the encapsulation concept of Object Oriented Programming.
Using only static methods, goes against encapsulation principle, it is possibly wrong but I can't tell for sure.
I hope this helped you and gave you a good direction to go on with your study.
PS:
To return multiple results, you should return an array of variables, not just a variable.
You can also return nothing and just have it do the job to a needed array. This FORCES you though to make this array public. (Not a good practice)
Finally if multiple value returns are needed to just print them on the console... well, just do it in the method, no need to return anything really.
You don't need to return anything, being that the methods are printing out all the values.
You can change them into void methods, for example:
public static void asterisk(int lowest, int highest) {
//loops and if statements
//no return statement!
}
The code in the methods will run and voila, you are done!
EDIT: That being said, there's a lot more than can be done to make this code more Java-like, but for now this will work.
mmmmm...you can return types, and (int lowestRange, int highestRange) its not a type. Look at the method definition
public static int Asterisk(int lowestRange, int highestRange)
the return type is declared as int, so you should return an int value. You can do something like
return lowestRange;
return 1;
with that in consideration, the error should dissapear. The question is, why do you need to return a value? From what i've read, your methods are supose to print stuff, not to return stuff...
The return statements are out of the method. You have to put them before the close method brackets.
public class MyClass{
public int sum (int a, int b){
return a + b;
} // The return have to be before this brackets
}

Write a recursive method that returns the number of occurences of 'A' in the string it is passed

So I've been fiddling with this problem for the past hour. I keep getting unexpected type error. It appears to be from a confliction between charAt and s.length. Any ideas on what could fix that?
class lab7
{
public static void main(String[] args)
{
String s = ("BCA");
}
public static String recursion(String s)
{
if (s.length()>=0)
{
if(s.charAt(s.length()) = A)
{
count++;
}
s.substring(0, s.length()-1);
}
return count;
}
}
There are several issues with this code, including some significant logic errors. However, the specific error you're getting is probably here:
if(s.charAt(s.length()) = A)
First, note that you're using = instead of ==, which does an assignment rather than a comparison. Also note that A should be in single quotes to be a character literal. Right now, Java thinks A is the name of a variable, which isn't defined. Finally, note that strings are zero-indexed, so looking up the character at position s.length() will give you a bounds error.
I hope this helps you get started! As a hint, although your function is named "recursion," does it actually use recursion?
Following code uses String class. For performance critical applications you might want to use StringBuffer / StringBuilder class accordingly.
class StringCounter
{
public static void main (String[] args)
{
int count = returnCount("ABCDABCDABCD", 0);
System.out.println(count);
}
public static int returnCount(String s, int count)
{
// You may want to do some validations here.
if(s.length()==0)
{
return count;
}
if(s.charAt(0)=='A')
{
return returnCount(s.substring(1), count+1);
}
else
{
return returnCount(s.substring(1), count);
}
}
}
The code simply slices the String parameter one character at a time and checks for the required character. Further on every invoke it will update the count and String parameter.
Any ideas on what could fix that?
Your function is not recursive. Recursive functions call themselves with manipulated/updated parameters.
As a thumb rule in recursive functions, always think in terms of manipulating function parameters.
Always have a base case that will terminate recursive calls.
Consider this snippet:
static int countA(String str) {
if (str == null || str.length() == 0) { /* nothing or "" contains 0 A's */
return 0;
}
return (str.charAt(0) == 'A' ? 1 : 0 ) /* 0 or 1 A's in first character */
+ countA(str.substring(1)); /* plus no. of A's in the rest */
}
And you call the function like this:
int a = countA("ABAABA"); /* a is 4 */
I realize now that this question was school related, but at least this snippet works as an exercise in understanding recursion.

Categories