[英]How do I shorten the java code for my loop
這里的初學者。 我希望能夠向用戶提問。 如果用戶的回答為空或僅包含空格,則應打印出錯誤,然后返回未回答的問題。 因此創建一個循環,直到問題被回答為止。 請參見下面的代碼:
do {
while(true) {
System.out.print("Dog's name: ");
String dogName = scan.nextLine().toLowerCase().trim();
if(dogName.isEmpty()) {
System.out.println("Error: This can't be empty.");
continue;
}
do {
while(true) {
System.out.print("Breed: ");
String breed = scan.nextLine().toLowerCase().trim();
if(breed.isEmpty()) {
System.out.println("Error: Breed can't be empty.");
continue;
}
該代碼有效,但變得非常重復且冗長。 有沒有更短,更快的方式編寫此代碼? 謝謝。
這是功能的理想用例。 一個函數封裝了一段您需要多次的代碼,並允許通過參數輸入和通過返回類型輸出。
我建議閱讀有關如何使用函數的Java初學者教程(如果函數屬於某個對象,即非靜態 方法,在Java中也稱為方法 )。
函數(有時也稱為其他語言的過程)是過程編程的基本構建塊,因此,我建議您也了解該主題。 在您的特定情況下,該函數可能如下所示:
String input(String label)
{
System.out.print(label+": ");
String s = scan.nextLine().toLowerCase().trim(); // assuming "scan" is defined in the enclosing class
if(s.isEmpty())
{
System.out.println("Error: "+label+" can't be empty.");
return input(label);
}
return s;
}
這是一個遞歸函數,但是您也可以迭代地進行。
為將問題作為參數的代碼創建一個方法,如果輸入錯誤,則需要詢問相同的問題,對相同的問題調用相同的方法(遞歸)。
偽代碼::
public void test(String s) {
System.out.print(s + ": ");
String input = scan.nextLine().toLowerCase().trim();
if(dogName.isEmpty()) {
System.out.println("Error: This can't be empty.");
test(s);
} else {
return input;
}
閱讀有關遞歸的內容 。
您可以嘗試這樣的操作,這樣您可以有很多問題,但是代碼數量相同,這只是為了說明這一點,可能無法完全解決問題
String questions[] = {"Dog's name: ","Breed: "};
for (int i = 0; i < questions.length; i++) {
System.out.print(questions[i]);
Scanner scan = new Scanner(System.in);
String answer = null;
while(!(answer = scan.nextLine()).isEmpty()) {
System.out.print("You answered: " + answer + "\n");
}
}
你可以這樣做 :
while ((dogName = scan.nextLine().toLowerCase().trim()).isEmpty()) {
System.out.println("Error: This can't be empty.");
}
// Use dogName not empty
while ((breed = scan.nextLine().toLowerCase().trim()).isEmpty()) {
System.out.println("Error: Breed can't be empty.");
}
// Use breed not empty
最好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.