簡體   English   中英

防止程序在用戶在Java中輸入錯誤的輸入后退出的正確方法是什么?

[英]What is the proper way to prevent a program from exiting after a user enters wrong input in Java?

任務

設計並實現一個應用程序,該應用程序讀取一個整數值,並打印出2到其輸入值(含)之間的所有偶數整數之和。 如果輸入值小於2,則輸出一條錯誤消息。

注意:該課程是在while循環中進行的,而不是其他循環(例如for循環等)

問題

我的所有工作都在進行中,但是關於我的編寫方式有些不對勁。 我目前有一個while循環while(programOn)來保持程序運行。 沒有此while循環,如果用戶輸入的數字< 2 ,則要求用戶再次嘗試,但是如果用戶再次嘗試,則程序退出,而不是在程序中運行新輸入。 因此,我創建了while循環來強制程序打開,直到用戶鍵入可接受的輸入為止。

-關於此事,我感到很hacky和不正確,我真的很感謝對我的方法進行的一些驗證。

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;
  }
}


}

這是因為驗證是通過if條件完成的。 您需要的是一個while循環,只要用戶input less than 2,它就會一直請求輸入,下面是執行此操作的代碼段:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM