I'm currently working on a college Java project, and I'm stuck. 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)
Test your function in a Java application program.
Sample run 1:
Enter an integer: 10
All the numbers lower than 10 and composed only with digits 1 and/or 3: 3, 1
Sample run 2:
Enter an integer: 20
All the numbers lower than 20 and composed only with digits 1 and/or 3: 13, 11, 3, 1
Note 1: This program should only accept positive integer values.
Note 2: All the outputs should be in the same line, separated with a comma. 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.
I would use an iterative approach here, starting with 1 up until, but not including, the input number. Then, loop over each number and ensure that every digit be 1 or 3, using the modulus:
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:
MATCH: 1
MATCH: 3
MATCH: 11
MATCH: 13
MATCH: 31
MATCH: 33
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.