Loop user input until conditions met - java

I need to ask the user to input a number to be used as the start of a range, and then input another number that is the end of the range. The start number has to be 0 or greater and the end number cannot be larger than 1000. Both numbers must be divisible by 10. I have found a way to meet these conditions, however if they are not met my program just tells the user that their input was incorrect. Is it possible for me to code it so that after the user inputs it will check to make sure the conditions are met, and if they are not loop back and make them input again. Here is the code I have so far.
Scanner keyboard = new Scanner(System.in);
int startr;
int endr;
System.out.println("Enter the Starting Number of the Range: ");
startr=keyboard.nextInt();
if(startr%10==0&&startr>=0){
System.out.println("Enter the Ending Number of the Range: ");
endr=keyboard.nextInt();
if(endr%10==0&&endr<=1000){
}else{
System.out.println("Numbers is not divisible by 10");
}
}else{
System.out.println("Numbers is not divisible by 10");
}

Easy with do-while:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
System.out.println("Enter the Starting Number of the Range: ");
startr = keyboard.nextInt();
if(startr % 10 == 0 && startr >= 0)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
good = false;
do
{
System.out.println("Enter the Ending Number of the Range: ");
endr = keyboard.nextInt();
if(endr % 10 == 0 && endr <= 1000)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
// do stuff

You need to use a while, something like:
while conditionsMet is false
// gather input and verify
if user input valid then
conditionsMet = true;
end loop
should do it.

The all-purpose procedure is:
Read the input in an infinite loop.
Use a break; statement to exit the loop when the conditions are met.
Example:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
for (;;) {
System.out.println("Enter the starting number of the range: ");
startr = keyboard.nextInt();
if (startr >= 0 && startr % 10 == 0) break;
System.out.println("Number must be >= 0 and divisible by 10.");
}
for (;;) {
System.out.println("Enter the ending number of the range: ");
endr = keyboard.nextInt();
if (endr <= 1000 && endr % 10 == 0) break;
System.out.println("Number must be <= 1000 and divisible by 10.");
}
If after invalid input you want to display just the error message without repeating the initial prompt message, move the initial prompt message just above/outside the loop.
If you do not have need for the separate error message, you can re-arrange the code to use a do-while loop to check the conditions, which is just a little shorter:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
do {
System.out.println("Enter the starting number of the range.");
System.out.println("Number must be >= 0 and divisible by 10: ");
startr = keyboard.nextInt();
} while (!(startr >= 0 && startr % 10 == 0));
do {
System.out.println("Enter the ending number of the range.");
System.out.println("Number must be <= 1000 and divisible by 10: ");
endr = keyboard.nextInt();
} while (!(endr <= 1000 && endr % 10 == 0));

Related

Problem in program to input a 3 digit number and check which digits are even and replace it with odd digits

Problem while entering a 3 digit no and getting no result. after entering 123 and when 2 is detected as even, and if user enters 7, it should display 173. but the program is immediately ending. It might be a problem in the last 0 check if-block. but removing it also doesn't help. Thanks in advance!
// in 3 dig, check even dig., replace them with odd and disp.
import java.util.*;
public class p24123 {
public static void main(String[] args) {
int n,h,t,o,m,z=0,z1=0,z2=0,fn;
Scanner ob = new Scanner(System.in);
n=ob.nextInt();
if(n>99&&n<1000){
h= n/100;
o=n%10;
m=n/10;
t=m%10;
if(h%2==0){
z=h;
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit"+h+" with \n");
z=ob.nextInt();
if(z%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z=h;
}
else if(t%2==0) {
System.out.println("Condition enter bokachpda");
z1 = t;
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit" + t + " with \n");
z1 = ob.nextInt();
if (z % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
z1 = t;
}
}
else if(o%2==0){
z2=o;
System.out.println("Enter the odd number you would like to replace the EVEN one's digit"+h+" with \n");
z2=ob.nextInt();
if(z2%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z2=o;
}
}
else if(2==2){
if(h<1||t<1||o<1||z<1||z1<1||z2<1){
System.out.println("Error");
System.exit(0);
}
}
fn=z*100+z1*10+z;
}
}
}
}
Here's your code cleaned up and fixed. I modified as little as possible to keep it at a level a beginner would be comfortable with. Some improvements to be made:
Repeated code like this screams, "Put me in my own function!"
A loop can be used to handle any number of digits, not just three.
Error checking/handling. You should handle bad input. What if the user enters "hello" instead of a number?
Improvements I made:
Your original code never printed a result.
Better formatting. It makes the code easier to read.
Descriptive variable names!
Scanner ob = new Scanner(System.in);
int n = ob.nextInt();
if (n > 99 && n < 1000) {
int hundredsDigit = n / 100;
int tensDigit = n / 10 % 10;
int onesDigit = n % 10;
if (hundredsDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit " + hundredsDigit +" with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
hundredsDigit = replacementDigit;
}
}
if (tensDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit " + tensDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
tensDigit = replacementDigit;
}
}
if (onesDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN one's digit " + onesDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
onesDigit = replacementDigit;
}
}
System.out.println(hundredsDigit * 100 + tensDigit * 10 + onesDigit);
}

How to make a number invalid

Create a new program called minusSentinel2.
Prompt the user to enter whole numbers between 1 and 100. Allow the user to enter as many numbers as desired.
If an invalid number is entered, print "Invalid entry." Prompt the user again until a valid number is entered.
Once -1 is entered, the program stops and prints the largest number entered with the text "The largest number entered is: "
I am having some trouble on the "Invalid entry." part. When I type a number greater than 100, "Invalid entry." does not get printed. How do I fix this? Thank you!
import java.util.*;
public class minusSentinel2
{
public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter a number between 1-100 (type -1 to quit):");
int number = console.nextInt();
int max = number;
if (number < 1 && number > 100)//chekcs if value is valid
{
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
console.next();
}
while (number != -1)
{
number = console.nextInt();
if (number > max)
{
max = number;
}
}
System.out.print("The largest number entered is: " + max);
}
}
Firstly, I suggest you to don't copy and paste what we ask you to do, and just reformulates with only necessary parts for us.
For your issue, this condition is wrong:
if (number < 1 && number > 100)
It correspond to "lower than 1 and bigger than 100".
So, instead of && (and) operator, use || (or) operator like that :
if (number < 1 || number > 100) {
// it's not valid because lower than 1 or greater than 100
}
Finally, what you are doing seems to have another issue.
If you enter an invalid number, it will ask again only one time, and not same the new value. So, I suggest you to use while loop like that :
int number = 0;
while(number < 1 || number > 100) {
number = console.nextInt();
if (number < 1 || number > 100) {
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
}
}
int max = number;
To conclude, this is the full code:
Scanner console = new Scanner(System.in); // create scanner
int number = 0; // create new variable that will be used outside of while loop
while (number < 1 || number > 100) { // while the number isn't valid
System.out.println("Enter a number between 1-100 (type -1 to quit):");
number = console.nextInt(); // wait for user input
if (number == -1) { // stop program
console.close();
return;
} else if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
}
}
System.out.println("Now enter all number that you want. End with -1.");
int max = number; // create new max value
while (number != -1) {
number = console.nextInt();
if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
} else if (number > max) { // if number is upper than current one
max = number;
// here you can do something like that:
// System.out.println("New max value: " + max);
} else {
// the value is value but not upper than current one, so we can write:
// System.out.println("This value isn't upper to " + max);
}
}
System.out.print("The largest number entered is: " + max);
console.close();

how to check in java that input is an integer and is in certain range by using hasNextInt()

I want a user to enter a number which is an int and is between 1 and 8. I want to keep prompting the user until the number is between 1 and 8 and it is an integer.
What I've tried:
System.out.println("Enter number between 1 and 8");
while(!console.hasNextInt())
{
System.out.println("not valid try again between 1-8");
console.next();
}
int number = console.nextInt();
while (number < 1 || number > 8)
{
System.out.println("number is not between 1 and 8 try again ");
number = console.nextInt(); // the problem is here because user might enter string or double.
}
how can I make my program more robust?
Many thanks,
something like:
int number;
System.out.println("enter a number between 1 and 8");
do {
while (!console.hasNextInt()) {
console.nextLine(); // consume input
System.out.println("not an integer. try again");
}
number = Integer.parseInt(console.nextLine());
if(number < 1 || number > 8)
System.out.println("number is not between 1 and 8 try again ");
} while (number < 1 || number > 8);
// do something with number

how to display whether the number is a multiple of 4 or not using loops

The question is:
Write a program that prompts the user to enter an integer and displays whether the number is a multiple of 4 or not. The program stops reading integers, when the user inputs a negative value. It shows at the end the total number of values entered which are multiple of 4.
Here is my progress so far:
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n;
while ((n = input.nextInt()) >= 0) {
if ( n%4 == 0) {
System.out.print(n + " is a multiple of 4");
}
else {
System.out.print(n + " is not a multiple of 4");
}
}
My problem is that I don't how to let the loop to keep executing until the user types in 0.
change the line
while((n = input.nextInt()) >= 0)
to
while((n = input.nextInt()) != 0)
This will keep the loop running until a zero is entered
Actually, 0 isn't a negative number, so you don't need to stop at 0. Your code is correct!

Java loops and zero divisor

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.

Categories