How can I ask the user to re-enter their choice? The 2019 Stack Overflow Developer Survey Results Are InRepetition of the program?How do I efficiently iterate over each entry in a Java Map?How can I concatenate two arrays in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How can I create an executable JAR with dependencies using Maven?How do I determine whether an array contains a particular value in Java?How can I convert a stack trace to a string?How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?Would it make any difference giving arguments using scanner class instead of command line arguments?

Why didn't the Event Horizon Telescope team mention Sagittarius A*?

Identify boardgame from Big movie

Deal with toxic manager when you can't quit

How come people say “Would of”?

Did Section 31 appear in Star Trek: The Next Generation?

The difference between dialogue marks

What is the accessibility of a package's `Private` context variables?

Did 3000BC Egyptians use meteoric iron weapons?

Why do we hear so much about the Trump administration deciding to impose and then remove tariffs?

Does the shape of a die affect the probability of a number being rolled?

Worn-tile Scrabble

Feature engineering suggestion required

Return to UK after having been refused entry years ago

Can you compress metal and what would be the consequences?

Should I use my personal e-mail address, or my workplace one, when registering to external websites for work purposes?

How to save as into a customized destination on macOS?

Is this app Icon Browser Safe/Legit?

What is the meaning of the verb "bear" in this context?

What does ひと匙 mean in this manga and has it been used colloquially?

A poker game description that does not feel gimmicky

Am I thawing this London Broil safely?

Time travel alters history but people keep saying nothing's changed

Can a rogue use sneak attack with weapons that have the thrown property even if they are not thrown?

Aging parents with no investments



How can I ask the user to re-enter their choice?



The 2019 Stack Overflow Developer Survey Results Are InRepetition of the program?How do I efficiently iterate over each entry in a Java Map?How can I concatenate two arrays in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How can I create an executable JAR with dependencies using Maven?How do I determine whether an array contains a particular value in Java?How can I convert a stack trace to a string?How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?Would it make any difference giving arguments using scanner class instead of command line arguments?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.



import java.util.Scanner; 

public class Ex1

public static void main(String args[]) number>999)
System.out.println("Error!: ");
else
System.out.println("The sum of all digits in " +number + " is " + sum);












share|improve this question

















  • 1





    Just put the whole code into a while loop.

    – Vinay Avasthi
    Mar 22 at 3:57











  • You turn to your book and class room material and research the topics of loops.

    – GhostCat
    Mar 22 at 3:58











  • As a really simple, conceptually example

    – MadProgrammer
    Mar 22 at 4:05

















1















I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.



import java.util.Scanner; 

public class Ex1

public static void main(String args[]) number>999)
System.out.println("Error!: ");
else
System.out.println("The sum of all digits in " +number + " is " + sum);












share|improve this question

















  • 1





    Just put the whole code into a while loop.

    – Vinay Avasthi
    Mar 22 at 3:57











  • You turn to your book and class room material and research the topics of loops.

    – GhostCat
    Mar 22 at 3:58











  • As a really simple, conceptually example

    – MadProgrammer
    Mar 22 at 4:05













1












1








1








I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.



import java.util.Scanner; 

public class Ex1

public static void main(String args[]) number>999)
System.out.println("Error!: ");
else
System.out.println("The sum of all digits in " +number + " is " + sum);












share|improve this question














I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.



import java.util.Scanner; 

public class Ex1

public static void main(String args[]) number>999)
System.out.println("Error!: ");
else
System.out.println("The sum of all digits in " +number + " is " + sum);









java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 3:56









Firenze21Firenze21

63




63







  • 1





    Just put the whole code into a while loop.

    – Vinay Avasthi
    Mar 22 at 3:57











  • You turn to your book and class room material and research the topics of loops.

    – GhostCat
    Mar 22 at 3:58











  • As a really simple, conceptually example

    – MadProgrammer
    Mar 22 at 4:05












  • 1





    Just put the whole code into a while loop.

    – Vinay Avasthi
    Mar 22 at 3:57











  • You turn to your book and class room material and research the topics of loops.

    – GhostCat
    Mar 22 at 3:58











  • As a really simple, conceptually example

    – MadProgrammer
    Mar 22 at 4:05







1




1





Just put the whole code into a while loop.

– Vinay Avasthi
Mar 22 at 3:57





Just put the whole code into a while loop.

– Vinay Avasthi
Mar 22 at 3:57













You turn to your book and class room material and research the topics of loops.

– GhostCat
Mar 22 at 3:58





You turn to your book and class room material and research the topics of loops.

– GhostCat
Mar 22 at 3:58













As a really simple, conceptually example

– MadProgrammer
Mar 22 at 4:05





As a really simple, conceptually example

– MadProgrammer
Mar 22 at 4:05












2 Answers
2






active

oldest

votes


















1














You will need to use a loop, which basically, well, loops around your code until a certain condition is met.



A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.



import java.util.Scanner;

class Main
public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

int num;

// Start a loop that will continue until the user enters a number between 1 and 10
while (true) num > 10)
System.out.println("Error: Number is not between 1 and 10!n");
else
// Exit the while loop, since we have a valid number
break;



System.out.println("Number entered is " + num);






Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:



import java.util.Scanner;

class Main
public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

int num;

// Start the loop
do

System.out.println("Please enter a number between 1 - 10:");

try
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
catch (NumberFormatException e)
System.out.println("Error: Please enter only numeric characters!");
num = -1;

// Skip the rest of the loop and return to the beginning
continue;


// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 while (num < 1






share|improve this answer

























  • A do-while loop would generally be easier (IMHO) and avoids the mess of while true

    – MadProgrammer
    Mar 22 at 4:04


















0














Try this, i just include the while loop in your code it will work fine.



public static void main(String[] args) 

private static int askInput(Scanner input)
int number = input.nextInt();
return number;






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292685%2fhow-can-i-ask-the-user-to-re-enter-their-choice%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You will need to use a loop, which basically, well, loops around your code until a certain condition is met.



    A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start a loop that will continue until the user enters a number between 1 and 10
    while (true) num > 10)
    System.out.println("Error: Number is not between 1 and 10!n");
    else
    // Exit the while loop, since we have a valid number
    break;



    System.out.println("Number entered is " + num);






    Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start the loop
    do

    System.out.println("Please enter a number between 1 - 10:");

    try
    // Attempt to capture the integer entered by the user. If the entry was not numeric, show
    // an appropriate error message.
    num = Integer.parseInt(scanner.nextLine());
    catch (NumberFormatException e)
    System.out.println("Error: Please enter only numeric characters!");
    num = -1;

    // Skip the rest of the loop and return to the beginning
    continue;


    // We have a valid integer input; let's make sure it's within the range we wanted.
    if (num < 1 while (num < 1






    share|improve this answer

























    • A do-while loop would generally be easier (IMHO) and avoids the mess of while true

      – MadProgrammer
      Mar 22 at 4:04















    1














    You will need to use a loop, which basically, well, loops around your code until a certain condition is met.



    A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start a loop that will continue until the user enters a number between 1 and 10
    while (true) num > 10)
    System.out.println("Error: Number is not between 1 and 10!n");
    else
    // Exit the while loop, since we have a valid number
    break;



    System.out.println("Number entered is " + num);






    Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start the loop
    do

    System.out.println("Please enter a number between 1 - 10:");

    try
    // Attempt to capture the integer entered by the user. If the entry was not numeric, show
    // an appropriate error message.
    num = Integer.parseInt(scanner.nextLine());
    catch (NumberFormatException e)
    System.out.println("Error: Please enter only numeric characters!");
    num = -1;

    // Skip the rest of the loop and return to the beginning
    continue;


    // We have a valid integer input; let's make sure it's within the range we wanted.
    if (num < 1 while (num < 1






    share|improve this answer

























    • A do-while loop would generally be easier (IMHO) and avoids the mess of while true

      – MadProgrammer
      Mar 22 at 4:04













    1












    1








    1







    You will need to use a loop, which basically, well, loops around your code until a certain condition is met.



    A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start a loop that will continue until the user enters a number between 1 and 10
    while (true) num > 10)
    System.out.println("Error: Number is not between 1 and 10!n");
    else
    // Exit the while loop, since we have a valid number
    break;



    System.out.println("Number entered is " + num);






    Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start the loop
    do

    System.out.println("Please enter a number between 1 - 10:");

    try
    // Attempt to capture the integer entered by the user. If the entry was not numeric, show
    // an appropriate error message.
    num = Integer.parseInt(scanner.nextLine());
    catch (NumberFormatException e)
    System.out.println("Error: Please enter only numeric characters!");
    num = -1;

    // Skip the rest of the loop and return to the beginning
    continue;


    // We have a valid integer input; let's make sure it's within the range we wanted.
    if (num < 1 while (num < 1






    share|improve this answer















    You will need to use a loop, which basically, well, loops around your code until a certain condition is met.



    A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start a loop that will continue until the user enters a number between 1 and 10
    while (true) num > 10)
    System.out.println("Error: Number is not between 1 and 10!n");
    else
    // Exit the while loop, since we have a valid number
    break;



    System.out.println("Number entered is " + num);






    Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:



    import java.util.Scanner;

    class Main
    public static void main(String[] args)

    Scanner scanner = new Scanner(System.in);

    int num;

    // Start the loop
    do

    System.out.println("Please enter a number between 1 - 10:");

    try
    // Attempt to capture the integer entered by the user. If the entry was not numeric, show
    // an appropriate error message.
    num = Integer.parseInt(scanner.nextLine());
    catch (NumberFormatException e)
    System.out.println("Error: Please enter only numeric characters!");
    num = -1;

    // Skip the rest of the loop and return to the beginning
    continue;


    // We have a valid integer input; let's make sure it's within the range we wanted.
    if (num < 1 while (num < 1







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 22 at 4:11

























    answered Mar 22 at 4:02









    ZephyrZephyr

    4,73721033




    4,73721033












    • A do-while loop would generally be easier (IMHO) and avoids the mess of while true

      – MadProgrammer
      Mar 22 at 4:04

















    • A do-while loop would generally be easier (IMHO) and avoids the mess of while true

      – MadProgrammer
      Mar 22 at 4:04
















    A do-while loop would generally be easier (IMHO) and avoids the mess of while true

    – MadProgrammer
    Mar 22 at 4:04





    A do-while loop would generally be easier (IMHO) and avoids the mess of while true

    – MadProgrammer
    Mar 22 at 4:04













    0














    Try this, i just include the while loop in your code it will work fine.



    public static void main(String[] args) 

    private static int askInput(Scanner input)
    int number = input.nextInt();
    return number;






    share|improve this answer



























      0














      Try this, i just include the while loop in your code it will work fine.



      public static void main(String[] args) 

      private static int askInput(Scanner input)
      int number = input.nextInt();
      return number;






      share|improve this answer

























        0












        0








        0







        Try this, i just include the while loop in your code it will work fine.



        public static void main(String[] args) 

        private static int askInput(Scanner input)
        int number = input.nextInt();
        return number;






        share|improve this answer













        Try this, i just include the while loop in your code it will work fine.



        public static void main(String[] args) 

        private static int askInput(Scanner input)
        int number = input.nextInt();
        return number;







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 4:24









        SandyKrishSandyKrish

        235




        235



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292685%2fhow-can-i-ask-the-user-to-re-enter-their-choice%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript