[英]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.