In the for
loop you need to check if i
is divisible by either num
or num1
and print the appropriate letter if it is.
Method nextLine
should be called after the call to nextInt
and before a subsequent call to nextLine
. Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("\nEnter 1st Number: ");
int num = input.nextInt();
input.nextLine();
System.out.print("\nEnter character: ");
String c = input.nextLine();
System.out.print("\nEnter 2nd Number: ");
int num1 = input.nextInt();
input.nextLine();
System.out.print("\nEnter character: ");
String c1 = input.nextLine();
for (int i = 1; i <= 10; i++) {
System.out.print(i);
if (i % num == 0) {
System.out.print(c);
}
if (i % num1 == 0) {
System.out.print(c1);
}
System.out.println();
}
}
Here is output from a sample run of the above code.
Enter 1st Number: 2
Enter character: &
Enter 2nd Number: 3
Enter character: *
1
2&
3*
4&
5
6&*
7
8&
9*
10&
You can also achieve the result using string concatenation, as shown in the below code.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("\nEnter 1st Number: ");
int num = input.nextInt();
input.nextLine();
System.out.print("\nEnter character: ");
String c = input.nextLine();
System.out.print("\nEnter 2nd Number: ");
int num1 = input.nextInt();
input.nextLine();
System.out.print("\nEnter character: ");
String c1 = input.nextLine();
String output;
for (int i = 1; i <= 10; i++) {
output = "" + i;
if (i % num == 0) {
output += c;
}
if (i % num1 == 0) {
output += c1;
}
System.out.println(output);
}
}