[英]How to check if an int contains specific numbers?
我目前正在从事一个大学 Java 项目,但被卡住了。 以下是上下文的分配详细信息:
编写一个函数,它接受整数 num 并显示所有仅由数字 1 和/或 3 组成的较小数字。(该程序可以接受任何整数值作为输入并提供适当的输出)
在 Java 应用程序中测试您的功能。
示例运行 1:
输入一个整数:10
所有小于 10 且仅由数字 1 和/或 3 组成的数字:3、1
示例运行 2:
输入一个整数:20
所有小于 20 且仅由数字 1 和/或 3 组成的数字:13、11、3、1
注 1:此程序应仅接受正整数值。
注2:所有输出应在同一行中,用逗号分隔。 您不应该在最后一个输出之后考虑逗号。
到目前为止,这就是我所做的:
import java.util.Scanner;
public class IntManipulator
{
public static void main (String[]args)
{
//initialize new system.in scanner object named input
Scanner input = new Scanner(System.in);
//prompt user to input an integer and use scanner object to store the integer in myInt
System.out.print("Enter an integer: ");
int myInt = input.nextInt();
//function call
intMethod(myInt);
//close input scanner object
input.close();
}
static void intMethod(int myInt)
{
System.out.print("All the numbers lower than " + myInt + " and composed only with digits 1 and/or 3: ");
for(int i=myInt; i>0; i--)
{
if()
{
System.out.print(i+", ");
}
}
}
}
我现在intMethod
的问题for
在我的intMethod
函数的for
循环中的if()
语句中放置什么,以便我只能打印包含 1 和/或 3 的i
值。
我会在这里使用迭代方法,从 1 开始,直到但不包括输入数字。 然后,使用模数遍历每个数字并确保每个数字都是 1 或 3:
public static void intMethod(int myInt) {
for (int i=1; i < myInt; ++i) {
int num = i;
while (num > 0) {
if (num % 10 != 1 && num % 10 != 3)
break;
num /= 10;
}
if (num == 0) {
System.out.println("MATCH: " + i);
}
}
}
对于intMethod(50)
的输入,生成了以下输出:
MATCH: 1
MATCH: 3
MATCH: 11
MATCH: 13
MATCH: 31
MATCH: 33
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.