这是函数的理想用例。函数封装了一段您需要多次的代码,并允许两个输入通过 参数 并通过输出 返回类型 。
我建议阅读关于如何使用函数的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; }
这是一个 递归 功能,但你也可以迭代地做。
你可以尝试这样的事情,这样你可以有很多问题,但是相同数量的代码,这是为了说明这个想法,可能无法完全发挥作用
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
最好
为代码创建一个方法,将问题作为参数,如果输入错误,则需要提出相同的问题,使用相同的问题调用相同的方法(递归)。
伪代码::
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; }
阅读 递归 。