How to check if an int contains specific numbers? - java

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

Related

I am getting an ArithmeticException Error for dividing by zero. But I am not. Why?

Here is the coding question for which I am trying to solve
Write a program that reads two numbers aa and bb from the keyboard and calculates and outputs to the console the arithmetic average of all numbers from the interval [a; b][a;b], which are divisible by 33.
Sample Input 1:
-5
12
Sample Output 1:
4.5
Here is my Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double average = 0;
int a = scanner.nextInt();
int b = scanner.nextInt();
Problem: Throws Arithmetic Exception
What is the problem?
Your variable i loops from -5 to 12. Then, you divide (a + b) / i (line 14).
0 is between -5 and 12. Thus, you will eventually divide by zero.
(I assume that line 13 is supposed to prevent this, but the way you have written it, it does not. In fact, 0 is among the very few values of i for which line 14 will actually be executed.)
According to your sample input and sample output, you need to add all the numbers in the range that are divisible by 3 and divide that total by how many different numbers are in the range.
Between -5 and 12, the numbers that are divisible by 3 are:
-3, 0, 3, 6, 9, 12
When you add them all together, you get 27.
And there are 6 different numbers altogether.
So the average is 27 divided by 6 which gives 4.5
Now for the code.
import java.util.Scanner;
public class RangeAvg {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter lower bound: ");
int a = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter upper bound: ");
int b = scanner.nextInt();
int lower = Math.min(a, b);
int upper = Math.max(a, b);
int total = 0;
int count = 0;
for (int i = lower; i <= upper; i++) {
if (i % 3 == 0) {
System.out.println(i);
total += i;
count++;
}
}
System.out.println("total = " + total);
System.out.println("count = " + count);
if (count > 0) {
double average = (double) total / count;
System.out.println("average = " + average);
}
else {
System.out.printf("No numbers divisible by 3 between %d and %d%n", lower, upper);
}
}
}
Below is a sample run:
Enter lower bound: -5
Enter upper bound: 12
-3
0
3
6
9
12
total = 27
count = 6
average = 4.5

receive input to find number of multiples

I'm having some trouble getting the correct output format for my homework. Here it is:
Write a program that accepts an integer n and an integer m from user and that prints a
complete line of output reporting the first m multiples of n. For example, if user input is:
m = 5, n = 3;
It should produce this output:
The first 5 multiples of 3 are 3, 6, 9, 12, and 15.
This is what I have so far:
import java.util.*;
public class Assignment2Part3 {
public static void main (String[] args) {
//declaring the two variables being entered
int n = 0;
int m = 0;
//declaring answer variable
int a = 0;
//declaring scanner input
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number you want to find multiples of");
n = input.nextInt();
while(true) {
System.out.println("Please enter the amount of multiples you want to see");
m = input.nextInt();
if (m <= 0) {
System.out.println("Please enter an integer greater than zero");
}
if (m > 0) {
break;
}
}
System.out.println("The first "+n+ " multiples of "+m+" are: ");
for (int i=1; i<=m; i++) {
a =i*n;
System.out.println(a);
}
}
}
This is what the output looks like right now:
Please enter the number you want to find multiples of
3
Please enter the amount of multiples you want to see
5
The first 3 multiples of 5 are:
3
6
9
12
15
How do I get the output to look like "The first 5 multiples of 3 are 3, 6, 9, 12, and 15." ?
NOTE: This assignment is for an introductory course and we have just covered for loops.
Printing them out on one line.
By changing System.out.println to System.out.print you can make multiple prints display on the same line.You also need to print a separator (", ") before every number (except the first), so that the numbers don't just pile up on top of each other.
Before the last number, you want to print "and".
You can do by altering the behaviour when the loop is at the final step (which is when i==m).
This gives something like this:
System.out.println("The first "+m+ " multiples of "+n+" are: ");
for (int i = 1; i <= m; ++i) {
if (i > 1) {
System.out.print(", ");
if (i==m) {
System.out.print("and ");
}
}
System.out.print(i*n);
}
System.out.println(".");

Processing numbers program

Firstly, I'm taking AP Computer Science this year, and this question is related to an exercise we were assigned in class. I have written the code, and verified that it meets the requirements to my knowledge, so this is not a topic searching for homework answers.
What I'm looking for is to see if there's a much simpler way to do this, or if there's anything I could improve on in writing my code. Any tips would be greatly appreciated, specific questions asked below the code.
The exercise is as follows: Write a program called ProcessingNumbers that does:
Accepts a user input as a string of numbers
Prints the smallest and largest of all the numbers supplied by the user
Print the sum of all the even numbers the user typed, along with the largest even number typed.
Here is the code:
import java.util.*;
public class ProcessingNumbers {
public static void main(String[] args) {
// Initialize variables and objects
Scanner sc = new Scanner(System.in);
ArrayList<Integer> al = new ArrayList();
int sumOfEven = 0;
// Initial input
System.out.print("Please input 10 integers, separated by spaces.");
// Stores 10 values from the scanner in the ArrayList
for(int i = 0; i < 10; i++) {
al.add(sc.nextInt());
}
// Sorts in ascending order
Collections.sort(al);
// Smallest and largest values section
int smallest = al.get(0);
int largest = al.get(al.size() - 1);
System.out.println("Your smallest value is " + smallest + " and your largest value is " + largest);
// Sum of Even numbers
int arrayLength = al.size();
for (int i = 0; i < al.size(); i++) {
if (al.get(i) % 2 == 0) {
sumOfEven += al.get(i);
}
}
System.out.println("The sum of all even numbers is " + sumOfEven);
// Last section, greatest even number
if (al.get(arrayLength - 1) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 1));
} else {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 2));
}
sc.close();
}
}
Here are specific questions I'd like answered, if possible:
Did I overthink this? Was there a much simpler, more streamlined way to solve the problem?
Was the use of an ArrayList mostly necessary? We haven't learned about them yet, I did get approval from my teacher to use them though.
How could I possibly code it so that there is no 10 integer limit?
This is my first time on Stackoverflow in quite some time, so let me know if anything's out of order.
Any advice is appreciated. Thanks!
Usage of the ArrayList wasn't necessary, however it does make it much simpler due to Collections.sort().
To remove the 10 integer limit you can ask the user how many numbers they want to enter:
int numbersToEnter = sc.nextInt();
for(int i = 0; i < numbersToEnter; i++) {
al.add(sc.nextInt());
}
Another note is that your last if-else to get the highest even integer doesn't work, you want to use a for loop, something like this:
for (int i = al.size() - 1; i >= 0; i--) {
if (al.get(i) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(i));
break;
}
I wouldn't say so. Your code is pretty straightforward and simple. You could break it up into separate methods to make it cleaner and more organized, though that isn't necessary unless you have sections of code that have to be run repeatedly or if you have long sections of code cluttering up your main method. You also could have just used al.size() instead of creating arrayLength.
It wasn't entirely necessary, though it is convenient. Now, regarding your next question, you definitely do want to use an ArrayList rather than a regular array if you want it to have a variable size, since arrays are created with a fixed size which can't be changed.
Here's an example:
int number;
System.out.print("Please input some integers, separated by spaces, followed by -1.");
number = sc.nextInt();
while (number != -1) {
al.add(number);
number = sc.nextInt();
}
Here is a solution that:
Doesn't use Scanner (it's a heavyweight when all you need is a line of text)
Doesn't have a strict limit to the number of numbers
Doesn't need to ask how many numbers
Doesn't waste space/time on a List
Handles the case when no numbers are entered
Handles the case when no even numbers are entered
Fails with NumberFormatException if non-integer is entered
Moved actual logic to separate method, so it can be mass tested
public static void main(String[] args) throws Exception {
System.out.println("Enter numbers, separated by spaces:");
processNumbers(new BufferedReader(new InputStreamReader(System.in)).readLine());
}
public static void processNumbers(String numbers) {
int min = 0, max = 0, sumOfEven = 0, maxEven = 1, count = 0;
if (! numbers.trim().isEmpty())
for (String value : numbers.trim().split("\\s+")) {
int number = Integer.parseInt(value);
if (count++ == 0)
min = max = number;
else if (number < min)
min = number;
else if (number > max)
max = number;
if ((number & 1) == 0) {
sumOfEven += number;
if (maxEven == 1 || number > maxEven)
maxEven = number;
}
}
if (count == 0)
System.out.println("No numbers entered");
else {
System.out.println("Smallest number: " + min);
System.out.println("Largest number: " + max);
if (maxEven == 1)
System.out.println("No even numbers entered");
else {
System.out.println("Sum of even numbers: " + sumOfEven);
System.out.println("Largest even number: " + maxEven);
}
}
}
Tests
Enter numbers, separated by spaces:
1 2 3 4 5 6 7 8 9 9
Smallest number: 1
Largest number: 9
Sum of even numbers: 20
Largest even number: 8
Enter numbers, separated by spaces:
1 3 5 7 9
Smallest number: 1
Largest number: 9
No even numbers entered
Enter numbers, separated by spaces:
-9 -8 -7 -6 -5 -4
Smallest number: -9
Largest number: -4
Sum of even numbers: -18
Largest even number: -4
Enter numbers, separated by spaces:
No numbers entered

Numbers to stop at the user's input

How do I make my program to stop at the user's input?
Here is my code:
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
if (i < x)
System.out.print(printFib(i) + " ");
else if (i > x)
break;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
So, if I enter 10 my program should stop before the number. Example:
Input: 10
Output: 0 1 1 2 3 5 8
But instead I get 0 1 1 2 3 5 8 13 21 34
How can I fix it?
int x = input.nextInt();
int fib = 0;
while (fib < x){
System.out.print(printFib(fib)+ " ");
fib++;
}
}
Don't use a for loop which right now you're using to print out Fibonacci numbers until the number of items printed is less than the entered number. Instead use a while loop that stops when the Fibonacci number itself is greater than the entered number.
Since this is likely homework, I'm just going to give this suggestion and not a code solution, but please give a solution a try, and if still stuck, come back with questions.
Pseudocode
Get value of x
create fibonacci variable and assign it 0
while fibonacci is less than x
display current fibonacci number
calculate next fibonacci number and place in variable
end while loop
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
int i = 0;
while ( printFib(i) <= x ) {
System.out.print(printFib(i) + " ");
i ++ ;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
While the number return from the printFib() method is less than and equal to the user input, it then runs the method. I've tried the code and it works.

Constructing a java program that reads numbers and says it's prime or lists its factors

The goal of my specific project is to write a program that will prompt the user to input two integers. The program will read the two integers and decide whether they are prime or not. if they are not the program will list the factors, otherwise it will simply print "prime" and ask the user repeatedly for two integers. Also, the program should print factors of all the numbers between the two given integers as well as the integers themselves. It will also give the average value of the prime numbers.
Goal is to make the final result look like this (assuming the two integers are 6 and 11):
Please enter two integers: 6 11
6: 2 3
7: Prime
8: 2 4
9: 3
10: 2 5
11: Prime
There are three prime numbers
The average value of the prime numbers is 9.00
Please enter two integers:
So here is my code:
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int r1, r2, i, c = 0;
System.out.println("Please enter two integers : ");
int num1 = input.nextInt();
int num2 = input.nextInt();
while (num1 > 0 && num2 > 0)
{
for (i = 2; i < num1; i++) {
r1 = num1 % i;
r2 = num2 % i;
if (r1 == 0 && r2 == 0)
System.out.println("Prime");
{
System.out.println(i+ "\t");
c++;
}
}
if (c == 0)
System.out.println("Prime");
System.out.print("Please enter two integers : ");
num1 = input.nextInt();
num2 = input.nextInt();
}
}}
And this is my output when inputting 6 and 11:
Please enter two integers :
6 11
2
3
4
5
Please enter two integers :
Now i have no idea where i went wrong but i feel i must be heading somewhat in the right direction. If both inputs are prime it will print prime. If one is prime and one is not it will do what i posted above.
Any and all help is appreciated. Thank you.
Well, I'm just glancing over briefly, but your problem lies within the for loop. You start i at 2, which is sensible for checking for factors. You then check, simultaneously, if both num1 and num2 are evenly divisible by i (at this point, 2). If they are, you print "Prime". Then you iterate and do it again. Think about that carefully: how closely does it match with what you think/thought you were doing?
If I had to guess, you are missing an else line after
if (r1 == 0 && r2 == 0)
System.out.println("Prime");
{
And also the condition for the "if" should probably be negated: if (!(r1 == 0 || r2 == 0)). That should at the very least be enough to get you going in the right direction.
Good luck!
A much shorter way to do.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}
public static void main(String[] args)
{
System.out.println("Please enter two integers : ");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
List<Integer> primenos = new ArrayList<Integer>();
List<Integer> result;
for(int i=num1; i<=num2; i++)
{
result = primeFactors(i);
System.out.print(i +":");
if(result.size()==1 && result.get(0)==i)
{
System.out.println(" prime");
primenos.add(i);
}
else
{
for (Integer j : result) {
System.out.print(" "+j);
}
}
System.out.println();
}
System.out.println("There are "+primenos.size()+" prime numbers");
int total = 0;
for(Integer j : primenos)
{
total+=j;
}
System.out.println("The average value of the prime numbers is "+total/primenos.size());
}
}
This is just one way of doing it.
You could find hundreds of algorithms if you google. Find one and modify to your needs.

Categories