[英]How to check if an int contains specific numbers?
I'm currently working on a college Java project, and I'm stuck.我目前正在从事一个大学 Java 项目,但被卡住了。 Here's the assignment details for context:
以下是上下文的分配详细信息:
Write a function that accepts integer num and displays all lower numbers composed only with digits 1 and/or 3. (This program can accept any integer value as an input and provide a proper output)
编写一个函数,它接受整数 num 并显示所有仅由数字 1 和/或 3 组成的较小数字。(该程序可以接受任何整数值作为输入并提供适当的输出)
Test your function in a Java application program.
在 Java 应用程序中测试您的功能。
Sample run 1:
示例运行 1:
Enter an integer: 10
输入一个整数:10
All the numbers lower than 10 and composed only with digits 1 and/or 3: 3, 1
所有小于 10 且仅由数字 1 和/或 3 组成的数字:3、1
Sample run 2:
示例运行 2:
Enter an integer: 20
输入一个整数:20
All the numbers lower than 20 and composed only with digits 1 and/or 3: 13, 11, 3, 1
所有小于 20 且仅由数字 1 和/或 3 组成的数字:13、11、3、1
Note 1: This program should only accept positive integer values.
注 1:此程序应仅接受正整数值。
Note 2: All the outputs should be in the same line, separated with a comma.注2:所有输出应在同一行中,用逗号分隔。 You should not consider a comma after the last output.
您不应该在最后一个输出之后考虑逗号。
So far, this is what I have made:到目前为止,这就是我所做的:
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+", ");
}
}
}
}
Where I'm stuck right now, is as to what to put in my if()
statement in my intMethod
function's for
loop, so that I can only print the values of i
that contain 1 and/or 3.我现在
intMethod
的问题for
在我的intMethod
函数的for
循环中的if()
语句中放置什么,以便我只能打印包含 1 和/或 3 的i
值。
I would use an iterative approach here, starting with 1 up until, but not including, the input number.我会在这里使用迭代方法,从 1 开始,直到但不包括输入数字。 Then, loop over each number and ensure that every digit be 1 or 3, using the modulus:
然后,使用模数遍历每个数字并确保每个数字都是 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);
}
}
}
For an input of intMethod(50)
, the following output was generated:对于
intMethod(50)
的输入,生成了以下输出:
MATCH: 1
MATCH: 3
MATCH: 11
MATCH: 13
MATCH: 31
MATCH: 33
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.