I am creating a program that will calculate two numbers. My issue is 0 will be an illegal input to the program but instead of asking again for two numbers.
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
I've done all the code and it mostly works and there is no visible error.
import java.util.*;
import java.util.Scanner.*;
public class MinilabLoopLogic
{
public static void main(String[ ] args)
{
int num1, num2, divisor, total;
Scanner kb = new Scanner(System.in); //you do it!
System.out.print("Please enter 2 integers (separated by spaces): ");
num1 = kb.nextInt();
num2 = kb.nextInt();
System.out.println("\n\nThis program will generate numbers BETWEEN "+ num1 + " " + num2);
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt();
while (divisor == 0)
{
divisor = kb.nextInt();
}
System.out.println("\n\n----------------------------------------");
//Be able to handle 1st number smaller
// OR 2nd number smalle
//Use the modulus operator to check if a number is divisible
if (num1 < num2)
{
for (total = num1+1; total < num2; total++ )
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
else
{
for (total = num1 - 1; total > num2; total--)
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
}
}//end main()
Your problem lies in your while loop looking for the divisor:
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
divisor = kb.nextInt(); // waits for more divisor input
}
You should output a string to tell the user what the problem is. say:
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
System.out.println("\nYou can't divide by 0. Try again!: ");
divisor = kb.nextInt(); // waits for more divisor input
}
Also, if you want them to have to re-enter the num1 and num2 then scanner input has to happen in that while loop.
You added the following in an edit:
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
That is because you just loop back to get another value when a zero is entered, without writing any new prompt text.
It also only gets a new divisor number, not "two different numbers". If you looped back to before "Please enter 2 integers", it'd actually end up prompting for all 3 numbers again.
Related
The Task
Design and implement an application that reads an integer value and prints out the sum of all EVEN integers between 2 and its input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly.
Note: the lesson was on while loops, not other loops such as for loop etc
The Issue
I have everything working, however something about how I have written this feels wrong. I currently have a while loop while(programOn) to keep the program running. without this while loop, if the user enters a number < 2, the user is asked to try again, however if the user tries again, the program exits instead of running the new input into the program. So, I created the while loop to force the program open until the user types an acceptable input.
- something about this feels hacky and incorrect i would really appreciate some validation on my method.
public static void main(String[] args){
int inputNumber;
int sum = 0;
boolean programOn = true;
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
inputNumber = scan.nextInt();
//include the original input to sum
sum = inputNumber;
while(programOn){
if(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
sum = inputNumber;
}else{
//from the number chosen divide until you reach 0
while(inputNumber != 0){
//subtract one from the number
inputNumber = (inputNumber - 1);
if((inputNumber % 2 == 0) && (inputNumber != 0)){
System.out.println(inputNumber);
//add the input to the sum
sum += inputNumber;
}
}
System.out.println("The sum is " + sum);
programOn = false;
}
}
}
That's because the validation is done by an if condition. What you need here is a while loop that keeps asking for inputs as long as user's input is less than 2, below is the code snippet that does this:
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
int inputNumber = scan.nextInt();
while(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
}
System.out.println(inputNumber);
I have a school assignment where I need to prompt the user for two numbers and display all the prime numbers in between I can't figure it out for the life of me. Here is my code, all it does is end as soon as I enter the two numbers.
public static void pg150Exersize1B() {
Scanner input = new Scanner(System.in);
int num, counter, num2;
System.out.println("Enter your low number");
num = input.nextInt();
System.out.println("Enter your high number");
num2 = input.nextInt();
counter = num;
while (num != num2) {
counter++;
if (num % counter == 0) {
if (counter == num) {
System.out.println(counter);
num++;
} else {
num++;
}
} else{
num++;
}
}
}
The first step in solving any coding-problem would be to transform the textual task into a basic code structure.
As an example, we can translate the task into the following main-routine:
display all prime numbers between two given numbers
could be translated to
print all numbers in a given range, if they are prime
which can be translated to the following pseudocode:
for i in [lower,upper]
if isPrime(i)
print(i)
This pseudocode can be translated pretty simple into the correct java-code.
Now we're missing one additional piece: the function isPrime(...). So let's apply the same pattern:
check, if a given number is prime
add some mathematical knowledge:
a number n is prime, if it's not divisible by any number in range [2,n)
and we wind up with
check, if a given number n isn't divisible by any number in the range [2,n)
I'll leave figuring the rest out to you.
Thanks for being honest and making clear this is homework.
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.
I thought my code was correct but when I ran it, my output statements at the bottom wouldnt produce. I'm asking the keyboard to enter any number and then to end by entering -1. My while loop includes adding numbers, creating a sum, as well as giving the amount of even numbers. When I test my code I've been entering just 1,2,3,4 hoping to produce 4 total numbers. 2 even, and a sum of 10. Why isnt' my code getting to the print statements?
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a number. Enter -1 to stop program.");
int num = sc.nextInt();
int counter = 0;
int even = 0;
int sum = 0;
while (num != -1)
{
counter += 1;
sum += num;
if (num%2 == 0)
{
even +=1;
}
}
System.out.println("You have entered "+ counter + "number(s)");
System.out.println("You have entered "+ even + "even numbers");
System.out.println("The sum for the numbers you entered is "+ sum);
}
You never get the input again so the loop runs infinitely. You need to get the value again.
while (num != -1)
{
...
num = sc.nextInt();
}
num gets set before you enter the loop.
So, when does the num change inside the while loop? It doesn't. That's why your code won't exit the loop.
I suggest moving the
num = sc.nextInt();
inside the loop.
My task is to write a java program that first asks the user how many numbers will be inputted, then outputs how many odd and even numbers that were entered. It is restricted to ints 0-100. My question is: What am I missing in my code?
import java.util.Scanner;
public class Clancy_Lab_06_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
n++;
}
int odd = 0;
int even = 0;
while (n >= 0 || n <= 100) {
n = input.nextInt();
if (n % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println(even + "even" + odd + "odd");
}
}
Second while loop is infinite. Relplace it with something like this:
for (int i = 0; i < n; i++) {
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also I don't understand why are you incrementing n in first loop. For example when you will first give -5, you will be asked to re-enter the number. Then you type -1, but it gets incremented and in fact program processes 0, altough user typed -1. In my opinion it is not how it suppose to work and you should just remove this n++.
As you asked in comment - the same using while loop:
while(n > 0) {
n--;
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also it is good idea to close input when you no longer need it (for example at the end of main method)
input.close();
You had two issues - first you were incrementing n in the first loop, rather than waiting for the user to enter a valid number.
In the second loop, you weren't comparing the number of entries the user WANTED to make with the number they HAD made - you were over-writing the former with the new number.
This version should work, although I've not tested it as I don't have java on this machine.
Note that we now sit and wait for both inputs, and use different variable names for the "how many numbers will you enter" (n) and "what is the next number you wish to enter" (num) variables? Along with a new variable i to keep track of how many numbers the user has entered.
import java.util.Scanner;
public class Clancy_Lab_06_03
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int n;
System.out.println ("How many numbers will be entered?");
n = input.nextInt();
//Wait for a valid input
while (n < 0 || n > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
//Setup variables for the loop
int odd = 0;
int even = 0;
int num;
//Keep counting up until we hit n (where n is the number of entries the user just said they want to make)
for(int i = 0; i < n; i++)
{
//Changed this, because you were over-writing n (remember, n is the number of entries the user wants to make)
//Get a new input
while (num < 0 || num > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//Check whether the user's input is even or odd
if (num % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(even + " even. " + odd + " odd.");
}
}
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("Enter an Integer number:");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
My suggestion to you is to have a clear separation of your requirements. From your post, you indicate you need to prompt the user for two distinct data items:
How many numbers will be entered (count)
The values to be analyzed
It is a good practice, especially when you are learning, to use meaningful names for your variables. You are using 'n' for a variable name, then reusing it for different purposes during execution. For you, it is obvious it was difficult to figure out what was 'n' at a particular part of the program.
Scanner input = new Scanner (System.in);
int count;
System.out.println ("How many numbers will be entered?");
count = input.nextInt();
//Wait for a valid input
while (count < 1 || count > 100)
{
System.out.println ("ERROR! Valid range 1-100. RE-Enter:");
count = input.nextInt();
}
Additionally, a count of zero should not be valid. It does not make sense to run a program to evaluate zero values (don't bother a program that does nothing). I believe the lowest count should be one instead.
int odd = 0;
int even = 0;
int value;
do
{
System.out.print("Enter a number between 0 and 100: ");
value = input.nextInt();
while (value < 0 || value > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
value = input.nextInt();
}
if (value % 2 == 0)
{
even++;
}
else
{
odd++;
}
count--; // decrement count to escape loop
} while (count > 0);
System.out.println(even + " even. " + odd + " odd.");
This example uses a do/while loop because in this case, it is OK to enter the loop at least once. This is because you do not allow the user to enter an invalid number of iterations in the first part of the program. I use that count variable directly for loop control (by decrementing its value down to 0), rather than creating another variable for loop control (for instance , 'i').
Another thing, slightly off topic, is that your requirements were not clear. You only indicated that the value was bounded to (inclusive) values between 0 and 100. However, how many times you needed to repeat the evaluation was not really clear. Most people assume 100 was also the upper bound for your counter variable. Because the requirement is not clear, checking a value greater or equal to 1 for the count might be valid, although highly improbable (you don't really want to repeat a million times).
Lastly, you have to pay attention to AND and OR logic in your code. As it was indicated, your second while loop:
while (n >= 0 || n <= 100) {}
Is infinite. Because an OR evaluation only needs one part to evaluate to TRUE, any number entered will allow the loop to continue. Obviously, the intent was not allow values greater than 100. However, entering 150 allows the loop to continue because 150 >= 0. Likewise, -90 also allows the loop to continue because -90 <= 100. This is when pseudocode helps when you are learning. You wanted to express "a VALUE between lower_limit AND upper_limit." If you reverse the logic to evaluate values outside the limit, then you can say " value below lower_limit OR above upper_limit." These pseudocode expressions are very helpful determining which logical operator you need.
I also took the liberty to add a message to prompt the user for a value. Your program expects the user to enter two numbers (count and value) but only one prompt message is provided; unless they enter an out of range value.
extract even numbers from arrayList
ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numberList.stream().filter(i -> i % 2 == 0).forEach(System.out::println);