我正在开发一个应用程序,它必须接收来自用户终端的多个输入,同时优雅地处理无效输入并提示用户重新输入。我的第一个想法是有一个while循环,它的主体将接受输入并验证它的有效性,当它获得有效输入时设置一个标志。此标志将标记应用程序所处的阶段,并将确定下一步需要哪种类型的输入,并且还将用作循环的终止条件。
虽然这是函数式的,但这看起来相当不优雅,我想知道是否有一种方法可以简单地编写一个函数,每当按下return键时就会调用该函数,以指示有新的输入需要解析。一些类似的东西
public class Interface {
public void receiveInput( final String input ){
// Parse 'input' for validity and forward it to the correct part of the program
}
}也许这可以通过extending一些Java类并重新实现它的一个函数来实现,这些函数通常可以处理这样的事件,但这可能是我的C++背景知识。
除了构建和单元测试所需的库之外,我不允许使用任何外部库。
发布于 2013-02-03 00:02:37
在从控制台读取时,您可以使用BufferedReader
BufferedReader br = new BufferedReader( new InputStreamReader( System.in));通过调用readLine函数,它将处理新行:
String readLine = br.readLine();您可以确定有一个类,其中将有一个读取信息并继续的函数。
下面是供您参考的示例代码
public class TestInput {
public String myReader(){
boolean isExit = true;
while (isExit){
System.out.print("$");
BufferedReader br = new BufferedReader( new InputStreamReader( System.in));
try {
String readLine = br.readLine();
if (readLine != null && readLine.trim().length() > 0){
if (readLine.equalsIgnoreCase("showlist")){
System.out.println("List 1");
System.out.println("List 2");
System.out.println("List 3");
} if (readLine.equalsIgnoreCase("shownewlist")){
System.out.println("New List 1");
System.out.println("New List 2");
} if (readLine.equalsIgnoreCase("exit")){
isExit = false;
}
} else {
System.out.println("Please enter proper instrictions");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Finished";
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Please Enter inputs for the questions asked");
TestInput ti = new TestInput();
String reader = ti.myReader();
System.out.println(reader);
}下面是输出:
Please Enter inputs for the questions asked
$showlist
List 1
List 2
List 3
$shownewlist
New List 1
New List 2
$exit
Finished希望这能有所帮助。
https://stackoverflow.com/questions/14663227
复制相似问题