How can I create a loop for user input (until the user enters valid input)? [duplicate]

假装没事ソ 提交于 2019-12-02 13:42:09
Jaffar Ramay

Use while loop with TRUE condition and break when you want to break.

package ex3;

        import java.util.Scanner;

        public class BankApp {

            public static void main(String[] args) {
                //displaying the welcome message
                System.out.println("Welcome to our bank.\nYour initial balance is 1000 SEK\n");
                //initializing all necessary variables
                double initialBalance = 1000;
                double userChoise = 0;
                double currentBalance;

                //asking user to enter expected amount
                System.out.println("Enter your amount you want to withdraw (in SEK): ");

                //creating new instance of the scanner class
                Scanner iScanner = new Scanner(System.in);

                while(true){

                //store into userChoise whatever amount is chosen by user
                userChoise = iScanner.nextDouble();
                //checking wheather the user inputs any valid amount or not. In this case it must be minimum 100 and maximum 1000.
                if(userChoise < 100 || userChoise > 1000)
                {
                    System.out.println("Error: Enter your amount again(in SEK): ");
                } 
                else {
                    currentBalance = initialBalance - userChoise;
                    System.out.printf("You have withdrawn %.2f\n", userChoise);
                    System.out.printf("Your current balance is %.2f\n", currentBalance);
                    break;
               }
           }
           }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!