我正在使用Java编程.
我正在尝试编写代码,可以识别用户是否在基于控制台的程序中按下回车键.
我怎么能用java做到这一点.有人告诉我,这可以使用扫描仪或缓冲输入阅读器完成.我不明白(或知道如何使用)缓冲输入阅读器.
我尝试使用扫描仪这样做,但按两次输入后程序终止,它不起作用
Scanner readinput = new Scanner(System.in);
String enterkey = "Hola";
System.out.print(enterkey);
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey == ""){
System.out.println("It works!");
Run Code Online (Sandbox Code Playgroud)
谢谢
- 编辑 - 以下代码使用equals字符串的方法而不是==
Scanner readinput = new Scanner(System.in);
String enterkey = "Hola";
System.out.print(enterkey);
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
System.out.println("It works!");
Run Code Online (Sandbox Code Playgroud)
如何做到这一点,以及使用缓冲输入阅读器做到这一点的优点是什么?
基于这个问题 增量变量名称?
我有一个arraylist'peopleHolder',它拥有各种"人物"物品.我想基于for循环自动创建'person'对象.我做了以下
peopleHolder.add(new person());
Run Code Online (Sandbox Code Playgroud)
我想从人类中调用方法.例如person.setAge; 我如何通过arraylist调用这些方法?我想要为每个对象设置值的方法.我看过这个答案:Java - 调用ArrayList中对象的方法
但是我认为解决方案依赖于调用静态方法,我希望在存储对象值时让对象特定于该对象.
谢谢
我试图使用compareToIgnoreCase对字符串数组进行排序.
该字符串包含名称ex:Billy Jean
当我尝试比较它们时,我得到一个空指针异常.我认为这是因为名字和姓氏之间的空格.我如何比较全名?
谢谢
class CompareStudentNames implements Comparator{
//Sorts the students by name ignoring case.
@Override
public int compare(Object o1, Object o2) {
String name1 = ((Student)o1).getName();
String name2 = ((Student)o2).getName();
return (name1.compareToIgnoreCase(name2));
}
Run Code Online (Sandbox Code Playgroud)
}
编辑---在使用比较学生姓名的代码中添加
private static void newInputFileReading(File f) throws FileNotFoundException{
String inputLine = null;
String [] inputSplit = new String[7];
Boolean proceed = false;
Scanner enterReader = new Scanner(System.in);
String name;
while(!proceed){
int stunum = -1;
try {
Scanner inputReader = new Scanner(f);
while(inputReader.hasNextLine()){
studentNM.add(new Student()); …Run Code Online (Sandbox Code Playgroud)