我有以下程序可以正常运行。与尝试执行相同操作的其他静态方法结合使用时会出现问题。在某些ide(BlueJ)上它可以正常工作,但在其他(eclipse)上则不能。
当它不起作用时,它将挂在input = kboard.nextLine();
我认为日食可能是一个更强大的想法。无论如何,如何在不关闭System.in的情况下关闭kboard以便将来使用?
/**
* Suppose you want to capture input from the keyboard
* but don't know what the user will type in. You could
* get text, or a number or you could just get [enter].
*
* How can you capture the input?
*/
import java.util.Scanner;
public class Kboard
{
public static void main(String[] args){
boolean text = false,
number = false,
enter = false;
String input = "";
Scanner kboard = new Scanner(System.in);
while(!input.equals("**")){
input = kboard.nextLine();
Scanner kstring = new Scanner(input);
/**
* if length() of input = 0 we must have gotten [enter]
*/
/**
* notice the order of the else if statements
* what happens if you reverse them?
*/
if(input.length() == 0) enter = true;
else if(kstring.hasNextDouble()) number = true;
else if(kstring.hasNext()) text = true;
System.out.println("[enter] : " + enter + "\n" +
"text : " + text + "\n" +
"number : " + number);
/**
* we close kstring before we create a new one
*/
kstring.close();
text = false;
number = false;
enter = false;
}
/**
* we close kboard before we exit
*/
kboard.close();
}
}