[英]Printing out numbers with only specific digits
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).我试图打印出低于作为命令行参数输入的特定数字(例如 430)包含特定数字(例如 2 和 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.
这样我的程序只打印包含 2 和 3 且小于 430 的数字,所以答案是:2、3、23、32 等。
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.你永远不会到达 else 块。
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.
在您的代码中,为什么要检查 0 和 1 而不是 2 和 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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.