Reputation: 13
I have to call it 5 times so it would print like this.
run:
I will call this routine 5 times and so on...
public class Method2 {
public static void main(String[] args) {
call();
}
static void call(){
System.out.println("I will call this routine 5 times");
for (int = i = 1; i<5; i++); //I don't know what I'm doing here.
}
}
I am new to method, I can call but I don't know how to put it in a loop. Thanks in advance !
Upvotes: 1
Views: 169
Reputation: 611
That's how for loop works ..
for (initialization; condition; increment/decrement) {
statement(s) //block of statements
}
so you actually need to place your print statement in
{}
static void call() {
for (int i = 0; i < 5; i++) {
System.out.println("I will call this routine 5 times");
}
}
If you want to print your statement 5 times, you either need to start your loop
from 0 to 5 (exclusive), like
for (int i = 0; i < 5; i++){
}
or from 1 to 5 (inclusive)
for (int i = 1; i <= 5; i++){
}
Upvotes: 1
Reputation: 20520
Your println
call has to happen inside the loop:
static void call(){
for (int i=1; i<=5; i++) {
System.out.println("I will call this routine 5 times");
}
}
Your code sets up an initial condition (i=1
); a condition that must be satisfied for each run of the loop (i<=5
); and an operation to happen at the end of each run of the loop (i++
).
Inside the loop (delimited by {
and }
) is the println
call, which happens five times.
One more stylistic note: most programmers would write the loop as starting from 0, and going up to (but not including) 5, like this:
for (int i=0; i<5; i++) { ... }
This is just because for most computing tasks it's more helpful if things are numbered from 0 rather than from 1. But it doesn't matter much here, because you're not using the value of i
for anything other than looping.
And an additional consideration: you talk about calling a routine five times. If you mean that you want the entire call()
method to be invoked five times, then you'd want your loop to sit inside the main()
method that invokes it, like this:
public static void main(String[] args) {
for (int i=1; i<=5; i++) {
call();
}
}
static void call(){
System.out.println("I will call this routine 5 times");
}
Upvotes: 0
Reputation: 1
well in C# it would look like this with for:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Here is the text 5 times");
}
Console.ReadLine();
and this would be the same with while:
static void Main(string[] args)
{
int i=0;
do
{
Console.WriteLine("Here is the text 5 times");
i++;
}
while (i < 5);
Console.ReadLine();
}
Upvotes: 0