簡體   English   中英

如何在代碼中添加或使用While循環

[英]How do i add the or use While loop in my code

我想使用while循環,以便它可以捕獲任何無效輸入,例如字母或隨機%% $ @@ ...等

我是Java的新手...非常感謝你們的幫助:)這是我正在從事的工作:

import java.util.Scanner; 

public class AreaCircle {

    public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // read the keyboard
System.out.println("This program will calculate the area of a circle");

System.out.println("Enter radius:");//Print to screen

double r = sc.nextDouble(); // Read in the double from the keyboard


double area = (3.14 *r * r); 
String output = "Radius: " + r + "\n";
output = output + "Area: " + area + "\n";
System.out.println("The area of the circle  is " + area);

    }
}

在nextDouble周圍放置一個try-catch塊...該文檔描述了掃描儀拋出的內容: http : //docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextDouble%28%29

while(True) {
  try {
    do_parsing()
    break;
  } catch (EvilException e) {
    continue;
  }
}

如果輸入無效,則nextDouble將拋出InputMismatchException 您可以將代碼圍繞在do / while循環中,在該循環中捕獲異常並在收到有效輸入后中斷循環。

boolean error = false;
do {
    try {
        System.out.println("Enter val: ");
        Scanner kbd = new Scanner(System.in);
        double r = kbd.nextDouble();
        error = false;
    } catch (InputMismatchException e) {
        error = true;
    }
}while(error);

處理用戶輸入非常簡單...

我最近有一個檢測無效用戶輸入的程序...

這是我使用循環執行的操作:

static String[] letters = {"a","b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"};

//declare an array of letters or number for your case
//and make a method to check if input key is present at the array..

 public int getIndexOf(char key){

        int charindex = -1;
        for(int index=0; index<letters.length; index++){            
            if(symbols[index] == key){
               charindex = index;
            }
        }

        return charindex;
    }

然后輸入://這樣就可以遍歷輸入

boolean sentinel = false;
char[] numbervalue= input.getText().toString().toCharArray();

 for (int z = 0; z < numbervalue.length; z++) {
                    int m = bal.getIndexOf(plaintext[z]);
                  if(m == -1){
                   sentinel = false;
                  break;
}
                }

然后您可以進行檢查...

if(sentinel){
//prompt the user that the input contains invalid characters
}else{
//continue with the processing....
}

就個人而言,我不會使用while循環,而會使用try / catch異常處理程序。 您可以繞一會兒循環,但是我不確定為什么會這樣做。 有一個稱為NumberFormatException的內置異常,它是針對像您所說的錯誤之類的。 所有你要做的就是

try {
    double r = sc.nextDouble();
}
catch( NumberFormatException e ) {
    //put a message or anything you want to tell the user that their input was weird.
}

從字面上看,它所要做的就是,如果輸入的內容不是數字,則進入catch塊並打印您的消息。 如果願意,可以將所有內容放入while循環中,以進行while循環。 希望這有效!

暫無
暫無

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

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