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

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현