Using two integers to find the multiples inbetween them - java

I am trying to display numbers divisible by two user-input integers using a 'for' loop statement. For example, if I were to input 5 and 30, I would get an output of "5 10 15 30". I've got the very basic setup so far, but I'm stuck right here. How can I use the variables to divide by each other within the loop statement?
import java.util.Scanner;
public class practice4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N_small= 0, N_big = 0;
System.out.printf("Enter the first number: ");
N_small = in.nextInt();
System.out.printf("Enter the second number: ");
N_big = in.nextInt();
if (N_small < N_big) {
for (int i = N_small; i == N_big; i++){
//Issue here! ***
System.out.printf("The numbers are: %d\n", i);
}
}
}
}
An example output in-case I'm not clear enough:
----------- Sample run 1:
Enter the first number: 5
Enter the second number: 30
The numbers are: 5 10 15 30
Bye
and
----------- Sample run 3:
Enter the first number: 7
Enter the second number: 25
The numbers are:
Bye.
Any help is greatly appreciated, thanks!

well if the first input is 5 and the second is 30
and the output is 5 10 15 30 (you are incrementing by (the first input)5 )
so if you input 10 and 25 the output should be 10 20 25 incrementing by (the first input).
if this is what you are trying to explain then your code should look like this
Scanner in = new Scanner(System.in);
int N_small= 0, N_big = 0 ,i;
System.out.printf("Enter the first number: ");
N_small = in.nextInt();
System.out.printf("Enter the second number: ");
N_big = in.nextInt();
if (N_small < N_big) {
System.out.printf("The numbers are:");
for (i = N_small; i < N_big+1 ; i=i+N_small){
if(i > N_big) System.out.println(N_big); else System.out.println(i);
}
}
}

Related

How can I make a loop in java with user input and have variables that are the last input and previous input?

I am trying to make a loop that takes user input until a number that is less than or equal to zero is entered or a number equal to the previous number is entered. I am having trouble figuring out how to code the user's previous input as a variable.
Directions
Write a program that has the class name Problem2 and that has the main
method.
In the main method, prompt the user to enter positive integers until
the user enters either a value that is less than or equal to 0 or
when the number entered is less than or equal to the number entered
previously.
A step is a positive difference between an entered integer and the
value entered prior to that integer. Calculate the number of big
steps (differences of more than 5) and the number of small steps
(differences of less than or equal to 5). Print out the big steps and
the small steps and the number that caused the program to end.
Examples:
Enter a positive integer: -10
Big steps: 0
Small steps: 0
Ending value: -10
Enter a positive integer: 1
Enter a positive integer: -3
Big steps: 0
Small steps: 0
Ending value: -3
Enter a positive integer: 4
Enter a positive integer: 12
Enter a positive integer: 13
Enter a positive integer: 15
Enter a positive integer: 21
Enter a positive integer: 26
Enter a positive integer: 21
Big steps: 2
Small steps: 3
Ending value: 21
Enter a positive integer: 71
Enter a positive integer: 72
Enter a positive integer: 72
Big steps: 0
Small steps: 1
Ending value: 72
Enter a positive integer: 45
Enter a positive integer: 62
Enter a positive integer: 0
Big steps: 1
Small steps: 0
Ending value: 0
How can I make a variable that is equal to the previous number is if it keeps changing?
How I understand it: You have five inputs total for example that is going to be entered by the user: 12, 15, 26, 31, 48.
Once you have 12, 15, 26 then the last number entered is 26 and the previous number entered is 15. When 31 and 48 are entered then the last number becomes 48 and the previous number becomes 31. If there are more numbers then the last input and previous input would continue to change until the loop ends.
How do I make a variable that would be equal to the number that is previously entered by the user if the numbers keep changing until the loop ends?
Am I understanding this correctly or am I going about it wrong?
My code so far:
public static void main(String args[]) {
// create variables
int numberOfBigSteps = 0;
int numberOfSmallSteps = 0;
int currentEntry = 0;
int previousEntry = 0;
Scanner scan = new Scanner(System.in);
while (currentEntry > 0) {
// loop user input until the user enters a number that is either
// a) less than or equal to 0
// b) less than the previous number
// currently it is not working at all and I can't enter any numbers
System.out.print("Enter a positive integer: ");
currentEntry = scan.nextInt();
if (currentEntry <= 0 || currentEntry <= previousEntry) {
if ((currentEntry - previousEntry) > 5)
// difference of more than 5
numberOfBigSteps++;
}
if ((currentEntry - previousEntry) <= 5) {
numberOfSmallSteps++;
if (currentEntry == previousEntry) {
numberOfSmallSteps++;
}
}
// output
System.out.println("Big steps: " + numberOfBigSteps);
System.out.println("Small steps: " + numberOfSmallSteps);
System.out.println("Ending value: " + currentEntry);
}
}
// currently it is not working at all and I can't enter any numbers
This is because you declared and initialized "currentEntry" to zero, and then start your loop with:
while (currentEntry > 0) {
So the code doesn't enter the loop at all because 0 is NEVER greater than 0.
After you get an integer, your logic is backwards:
if (currentEntry <= 0 || currentEntry <= previousEntry) {
if ((currentEntry - previousEntry) > 5) // difference of more than 5
numberOfBigSteps++;
}
You're saying that if the current number is negative or less than or equal to the previous number you should calculate the step value when in fact that is an ending condition where you'd simply stop the loop and display the outputs.
To store the previous number, which you're not currently doing, you'd simply put this line at the bottom of the loop:
previousEntry = currentEntry;
You were actually pretty close to a correct answer.
Here's my version:
// create variables
int numberOfBigSteps = 0;
int numberOfSmallSteps = 0;
int currentEntry = -1;
int previousEntry = -1;
boolean keepGettingNumbers = true;
Scanner scan = new Scanner(System.in);
while (keepGettingNumbers) {
System.out.print("Enter a positive integer: ");
currentEntry = scan.nextInt();
keepGettingNumbers = (currentEntry>0 && currentEntry>previousEntry);
if (keepGettingNumbers) {
if (previousEntry != -1) {
int step = currentEntry - previousEntry;
if (step>5) {
numberOfBigSteps++;
}
else {
numberOfSmallSteps++;
}
}
previousEntry = currentEntry;
}
}
// output
System.out.println("Big steps: " + numberOfBigSteps);
System.out.println("Small steps: " + numberOfSmallSteps);
System.out.println("Ending value: " + currentEntry);

How to check if an int contains specific numbers?

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

why does displayed number goes above the input number in java?

Currently, I am doing an assignment on displaying all odd numbers up to a user inputted specific odd number. The requirement is to include the input number, however, I don't understand why does the code always goes to the next Odd number compared to what user inputted. Please help.
import java.util.Scanner;
public class OddNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 0; i < capp_number; i+= 2){
startingNumber += 2;
System.out.println(startingNumber);
}
This is because i starts at 0 (It is even), and you are checking to see if it is less than capp_number (which should be odd), and then adding two to i. startingNumber starts at 1, so it is odd. So if the user enters 5 it will go like:
Iteration 1:
i (0) < 5 ? Yes:
print startingNumber+2
output: 3
i == 2
Iteration 2:
i (2) < 5 ? Yes:
print startingNumber +2
output: 5
i == 4
Iteration 3:
i (4) < 5 ? Yes:
print startingNumber +2
output: 7
i == 6
Iteration 4
i (6) < 5 No:
end loop
To fix this, start i at one:
for(int i = 1; i < capp_number; i+= 2)
Sorry, but why did you write this ?
while(startingNumber < capp_number);
i agree with a previous answer and think that there is no reason for this line. And also you should correct your loop as it was also mentioned in previous answer:for(int i = 0; i < capp_number; i+= 2)
Try this. You needed to initialise i to 1 within the for-loop. 1 is an odd number so instead of starting with an even number (0), you look for every odd number.
For example, if you start at 1: 1+2=3, 3+2=5, 5+2=7.... and so on.
For example, if you start at 0: 0+2=2, 2+2=4, 4+2=6.... and so on.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 1; i < capp_number; i += 2){
startingNumber += 2;
System.out.println(startingNumber);
}

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(".");

How do I get my code to process a given minimum value AND a value if < than given minimum

I am a Java newbie and have been working on this program for about a month. My program is a graduation planner that shows the student how much time and money it would take to finish a college degree. I would like my program to be able to recognize that the minimum # of CUs could be < than 12 if the student only has 6 or so CUs left until graduation, but I also need it to recognize if I enter a letter or negative number which I somehow managed to pull off at the top of the code. I tried to use sum == sum which isn't giving me the desired output. I think I need to put the while (loop) somewhere in there.
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
double rounded = 0;
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
double numTermsToCompletion = Math.ceil(sum / rounded);
System.out.println("Number of terms to completion: " + numTermsToCompletion);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToCompletion * 2890));
System.out.println("Number of months to completion: " + (numTermsToCompletion * 6));
}
}
The below code is the section that I think I am having trouble with because I need it to recognize that sometime a student may not have the minimum (12) CUs left and I would like it to check to make sure the minimum is met or recognize that less than the minimum is left and still process the input. I tried to reuse while (loop) cause I know that part of the program responds correctly when I try to enter a letter or negative number at the beginning of the code, but I obviously was not implementing the loop correctly when I tried to put it on the below code, the program runs but doesn't produce anything when it gets to that point in the code. It just runs and doesn't produce any errors. In summary, I would appreciate some assistance getting my code to realize that a student may not have the minimum CUs left (12) and may need < than that to graduate, but also not accept negative numbers or letters as input.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
So I moved sum == sum and I am a little closer to where I need to be. I still need to do some research because I am how getting the statement that tells me that I need to have a minimum of 12, but it still gives me the correct output.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
if (sum == sum) {
break;
}
} while (rounded < 12 || rounded > sum);
This is the output:
Total number of CUs for all courses: 8
How many CUs you are planning to take each term: 8
Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 :
Number of terms to completion: 1.0
Tuition cost based on number of terms to completion: $2890.0
Number of months to completion: 6.0
BUILD SUCCESSFUL (total time: 12 seconds)
Ok. From the recommendations I have received, I rethought the process and rewrote some of the code and it works a lot better. The problem now is if the user enters 0 from the beginning, this is the output:
Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.
Enter CUs for individual course then press enter: 0
Total number of CUs for all courses: 0
Number of terms to completion: 1
Tuition cost based on number of terms to completion: $2890
Number of months to completion: 6
BUILD SUCCESSFUL (total time: 2 seconds)
If you have 0 CUs left, you shouldn't have any terms left. It looks like I need to either change where my loop is false, or do something similar like I did here:
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
Below is the complete new code:
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
// Student enters the individual credits for each course remaining in their degree program
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
// loop checks to make sure inputs are positive numbers
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
// Calculates inputs from user
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
int numOfCUs = 0;
int numTermsToGraduation = 0;
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
} else {
numOfCUs = sum;
numTermsToGraduation = 1;
}
System.out.println("Number of terms to completion: " + numTermsToGraduation);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToGraduation * 2890));
System.out.println("Number of months to completion: " + (numTermsToGraduation * 6));
}
}
From what I could tell, you are trying to use "sum == sum" to tell you if the input value is an negative number or a letter. This is not correct, as sum==sum will always return true.
For checking if it is a number is positive, you should just use sum > 0.
As for checking if its actually a letter, and not a number, this is handled by your scanners when you check if the input is a number (hasNextInt).
It looks like you are using if (sum == sum) {...} to error check the value of sum. That is not what you want to do, because it is always going to equate to true. What you want to do is use a try {...} catch (InputMismatchException e) {...}. In your case, it would be set up as follows:
...
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
int exception = 1;
while (exception = 1) {
try {
int someNum = input.nextInt();
...
}
catch (InputMismatchException e) {
exception = 1;
System.out.println("Please enter the correct data type!");
}
}
...
At the first moment the InputMismatchException is thrown, the program will execute the code in the catch block.

Categories