I'm trying to print out the numbers that are below a specific number entered as a command line argument (eg 430) that contain specific digits (eg 2 and 3). So that my program prints only numbers containing 2 and 3 and are below 430, so the answer would be : 2,3,23,32, etc.
I've written a piece of code but for some reason I can't get it to work. Any help is appreciated ! Here's my code:
public static void main(String[] args) {
int input = Integer.parseInt(args[0]);
for(int i=0; i<input; i++) {
String test= Integer.toString(i);
for(int j=0; j<test.length(); j++) {
if((test.charAt(j) != '2') || (test.charAt(j)!='3')) {
}
else {
System.out.println("The digit is " + i);
}
}
}
}
You'll never reach the else block.
if((test.charAt(j) != '0')
|| (test.charAt(j)!='1')) {
}
Should be:
if((test.charAt(j) != '0')
&& (test.charAt(j)!='1')) {
}
Here is working code. In your code, why are you checking for 0 and 1 instead of 2 and 3.
public static void main(String[] args) {
int input = Integer.parseInt(args[0]);
int two = 0, three = 0;
for (int i = 0; i < input; i++) {
String test = Integer.toString(i);
if (i < 10 && (test.equals("2") || test.equals("3"))) {
System.out.println("The digit is " + i);
} else {
for (int j = 0; j < test.length(); j++) {
if (test.charAt(j) == '2') {
two++;
} else if ((test.charAt(j) == '3')) {
three++;
}
}
if (two >= 1 && three >= 1) {
System.out.println("The digit is " + i);
}
two = 0;
three = 0;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.