Reputation: 37
I'm trying to figure out a problem within the section of code I am required to write for an assignment. I am coding in Java. Everything in my code works perfectly except for (what I think to be) the loop condition.
This code is supposed to get 2 values, a and b. a refers to how many times the loop should be performed. b refers to a number. So if a = 5 and b = 5, the output should be:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
I will include my code and if anyone can help me fix my assignment or tell me what I am overlooking, that would be a huge help.
import java.util.Scanner;
public class MaxMultiples {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Maximum Number: ");
int maxnum = sc.nextInt();
System.out.print("Enter Multiplier: ");
int mult = sc.nextInt();
System.out.println("Displaying multiples of " + mult + ":");
int current = 1;
int result = 0;
for (int counter = 0; counter == maxnum; counter++);
{
result = mult * current;
System.out.println(mult + " x " + current + " = " + result);
current++;
}
}
}
Upvotes: 1
Views: 58
Reputation: 77
change your for loop as follows
for (int counter = 1; counter <= maxnum; counter++)
{
result = mult * current;
System.out.println(mult + " x " + current + " = " + result);
current++;
}
you are using ; at for (int counter = 1; counter <= maxnum; counter++); means you are terminating it at that point thats why it is executing only once
Upvotes: 0
Reputation: 1185
Following is working code you made two mistake one is after for loop ; and condition of for loop should be counter
import java.util.Scanner;
public class MaxMultiples{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Maximum Number: ");
int maxnum = sc.nextInt();
System.out.print("Enter Multiplier: ");
int mult = sc.nextInt();
System.out.println("Displaying multiples of " + mult + ":");
int current = 1;
int result = 0;
for (int counter = 0; counter < maxnum; counter++)
{
result = mult * current;
System.out.println(mult + " x " + current + " = " + result);
current++;
}
}
}
Upvotes: 0
Reputation: 393781
You have two errors :
Remove the ;
, since it ends the for loop (meaning you have an empty for loop) :
for (int counter = 0; counter == maxnum; counter++);
^
Change the stopping condition from ==
to <
or <=
, since the loop will never get executed if you initialize counter
to 0
and terminate it when it's not equal to maxnum
(assuming maxnum
is not 0
).
for (int counter = 0; counter == maxnum; counter++);
^
Upvotes: 5