I'm having trouble coding this program in JAVA
Ask the user an integer number then print 1 to n where is input number. if the number have a 1 skip that number and make sure match the length of n number to the output.
Example:
input: 22
output 2 3 4 5 6 7 8 9 20 22 23 24 25 26 27 28 29 30 32 33 34 35 - Total of 22 numbers
skipped all numbers with 1 and matched the length of the inputted numbers
I tried doing conditional statements, nested ifs and for loop but i failed and i badly need some lessons so i can understand the logic
CodePudding user response:
you can do something like this:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
int count = 0;
for (int i = 1; count < num; i ) {
if (String.valueOf(i).contains("1")) {
continue;
}
System.out.println(i);
count ;
}
sc.close();
}
}
Update:
If you do not want to use String.valueOf() you can go like this:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
int count = 0;
for (int i = 1; count < num; i ) {
int val = i;
boolean hasOne = false;
while (val > 0) {
if (val % 10 == 1) {
hasOne = true;
break;
}
val = val / 10;
}
if (hasOne) {
continue;
}
System.out.println(i);
count ;
}
sc.close();
}
}