Calling a method three times the most basic way you can - java

I want to know if there are basic ways to call a method multiple times. I am not allowed to use for, if, or else statements. I am suppose to write a method called test 1 and test 2, which calls the increase speed and decrease speed by 3 times. If anyone can offer me suggestions, I would appreciate it.
Requirements
increaseSpeed. The increaseSpeed method should add 10 to the speed
field each time it is called.
reduceSpeed. The reduceSpeed method should subtract 10 from the speed
field each time it is called.
write a method called test1 that calls increaseSpeed three times.
write a method called test2 that calls reduceSpeed three times.
program:
public void increaseSpeed()
{
speed += 10;
}
public void reduceSpeed()
{
speed -= 5;
}
public void test1(){
}
public void test2(){
}
}

You could simulate a for loop with a while loop:
public void test1() {
int i = 0;
while (i < 3) {
increaseSpeed();
++i;
}
}
Or, if you aren't allowed to use loops at all, you could just call the increaseSpeed three times:
public void test1() {
increaseSpeed();
increaseSpeed();
increaseSpeed();
}

We can also get more creative (a.k.a. pointless):
This first example requires Java 8, but it's a glorified FOR loop. You can replace 'forEach' with a map() or filter() that has an ignored output or one of the other Java stream processing items if you have an aversion to the word 'for'.
private static void test1() {
IntStream.range(0, 3).forEach(
i -> increaseSpeed()
);
}
This second example uses a switch + recursion because you also didn't mention anything about the 'switch' statement.
private static final int INITIAL_COUNT = 2; // 3 - 1
private static int numTimes = INITIAL_COUNT;
private static void test2() {
switch(numTimes) {
case 0:
numTimes = INITIAL_COUNT;
break;
default:
numTimes--;
test2();
break;
}
reduceSpeed();
}
Note that if you tried to submit either of these to a code review, you'll be rejected unless the project is run by a joker that doesn't care about code quality :)

You didnt mention while loop is prohibited, i assume it is okay to use it:
int i = 0;
while(i<3){
increaseSpeed();
i++;
}
Alternatively, you can either use do-while loop to implement your requirement or invoke the method 3 times..

public void test1(){
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
public void test2(){
decreaseSpeed();
decreaseSpeed();
decreaseSpeed();
}
For more general "solutions" and hacks have a look at these: C: Looping without using looping statements or recursion and
https://codegolf.stackexchange.com/questions/33196/loop-without-looping.

Using the given methods, the most effective and simple way would be to invoke it 3 times in a row:
public void test1() {
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
public void test2() {
decreaseSpeed();
decreaseSpeed();
decreaseSpeed();
}
A more flexible approach is using a recursive invocation, as described below:
public void test1() {
increaseSpeed(3);
}
public void test2() {
decreaseSpeed(3);
}
private void increaseSpeed(int numTimes) {
if (numTimes == 0) {
return;
}
increaseSpeed();
increaseSpeed(numTimes-1);
}
private void decreaseSpeed(int numTimes) {
if (numTimes == 0) {
return;
}
decreaseSpeed();
decreaseSpeed(numTimes-1);
}
Going a little bit beyond the question, if these tests model a real use case it probably is a good idea to review methods increaseSpeed() and decreaseSpeed() to prevent these multiple invocations.

Your test1 method should be recursive and it should take an Integer as parameter which will be the number of calls you want to make
So basically you should have something like this:
public void test1(int nbcalls) {
if (nbcalls-- > 0) {
increaseSpeed();
test1(nbcalls);
}
}
and you call you method like this :
test1(3);
You should do the same with test2(...) method

Related

Multiplication in Java using recursion

I am new to programming and I am writing a simple code in Java that is using recursion. I want to show the product of two numbers (from start to End). The return of the method is the multiplication of the numbers from start to end. (For Example: If the numbers are 1 and 3 then I want the method to return 6.
I managed to do the recursion but I am not sure if the code is effective at all. Here is my code so far. Thanks
public class ÜbungsblattSieben {
public static void main(String[] args) {
System.out.println(multiplyFromStartToEnd(1, 3));
}
public static int multiplyFromStartToEnd(int start, int end) {
if (start == end) {
return end;
} else {
return start * multiplyFromStartToEnd(++start, end);
}
}
}
Your code is as effective as a recursive multiplication can be. Well done.
That said, here are a few notes:
You may write start + 1 instead of ++start. Generally easier to read and understand. Also you do not have to change the start variable itself, you just want to pass a bigger number to the method call, thats all.
You may also want to properly indent your code (just hit the auto-format key in your IDE).
I would also suggest to rename your method to multiplyFromTo, but thats a very subjective note.
All in all, your code would then look like:
public class ÜbungsblattSieben {
public static void main (String[] args) {
System.out.println(multiplyFromStartToEnd(1, 3));
}
public static int multiplyFromTo(int start, int end) {
if (start == end) {
return end;
} else {
return start * multiplyFromStartToEnd(start + 1, end);
}
}
}
For reference, here is how an iterative version could look like:
int result = 1;
for (int i = start; i <= end; i++) {
result *= i;
}
System.out.println(result);
Obviously, this is a lot faster than recursion.

Java code does not return anything even though it is supposed to

I'm just new to Java OOP, and I hardly understand about the class and stuff. I tried to write some code to understand but I didn't succeed. Here is my code, I expected it to return the number of eggs but I don't know why it returns nothing.
class EggCounter {
private int egg;
{
egg = 0;
}
public void eggAdd()
{
egg = egg + 1;
}
public void eggBreak()
{
egg = egg - 1;
}
public void eggAddDozen()
{
egg = egg + 12;
}
public int getEgg()
{
return egg;
}
}
public class EggTest
{
public static void main(String[]args)
{
EggCounter egg = new EggCounter();
egg.eggAdd();
egg.eggAddDozen();
egg.eggBreak();
egg.getEgg();
}
}
It does return 12. Replace the egg.getEgg(); line in your main method with System.out.println(egg.getEgg()); and you will notice it prints 12.
It is returning, it's just that you do nothing with the return value of getEgg. What you need to do is store it into the variable or do something with it. return <value> only returns the given value to the callee, you must store it to use it. Example:
int eggCount = egg.getEgg();
System.out.println(eggCount);
Here, the assignment of eggCount calls egg.getEgg(). The call resolves when the number of eggs is returned, which assigns the return value to eggCount. Finally, it will print out eggCount. If you need the result of egg.getEgg() later, you can simply just output the following:
System.out.println(egg.getEgg());
How this works is the method egg.getEgg() is called. The return value is then resolved, which is passed into the print statement. This gets rid of storing it into a variable you can use later.

Return statement not working when calling another method

I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));

What classifies as a recursive function in Java

does this count as a recursive function...if no, then what is the reason. Which changes would classify it as such...thanks
public class Recursion {
public static void recursionFunc(int beginning_value){
if (beginning_value != 0){
System.out.println(beginning_value);
recursionFunc(beginning_value - 1);
}
}
public static void main(String[] args){
recursionFunc(10);
}
}
A function that calls itself, directly or indirectly, is called recursive. Your function calls itself, so it is definitely recursive.
Here is an example of recursive functions that calls themselves indirectly:
static void funcA(int x) {
if (x <= 0) return;
if (x % 2 == 0) {
funcB(x-1);
} else {
funcC(x-1);
}
}
static void funcB(int x) {
funcA(x-1);
}
static void funcC(int x) {
funcA(x-2);
}
Your method is a recursive method. A method is considered to be recursive when it calls itself again. All recursion methods should some sort of exit built into it, otherwise the method will yield an Stackoverflow error.
Here is a recursive method that does not have a exit built into it:
static void callAgain() {
callAgain();
}
Here's more details on recursive methods:
http://danzig.jct.ac.il/java_class/recursion.html

Multiple open and close curly brackets inside method. - Java

public class MyTestClass {
public static void main(String[] args) {
new MyTestClass().myMethod();
}
public void myMethod(){
{
//do something
}
{
//do something
}
{
//do something
}
}//method close
}//class close
What is the benefit of doing this? I have seen this kind of code.
It is not common practice to do this kind of thing, and I wouldn't do it normally.
They are defined as Blocks in the JLS, here.
Those inner blocks ( i.e. { ... } ) can serve a couple of purposes:
Blocks limit the scope of any variables declared within them; e.g.
public void foo() {
int i = 1;
{
int j = 2;
}
// Can't refer to the "j" declared here. But can declare a new one.
int j = 3;
}
However, I wouldn't recommend doing this. IMO, it's better to use different variable names OR refactor the code into smaller methods. Either way, most Java programmers would regard the { and } as annoying visual clutter.
Blocks can be used to attach labels.
HERE : {
...
break HERE; // breaks to the statement following the block
...
}
However, in practice you hardly ever see labelled break statements. And because they are so unusual, they tend to render the code less readable.
public void stuff() {
int i = 48;
{
int i = 21;
System.out.println(i); // prints 21
}
System.out.println(i); // prints 48
}
Basically, it's a way to create scopes smaller than entire function... Benefit?.. have the people stare at your code longer before they understand it... IMO it's bad style and should be avoided

Categories

Resources