我尝试使用Scanner
从控制台读取字符串对象并继续添加数据,直到用户按两次输入。我如何改进代码?
String text;
public void Settext() {
System.out.println("please enter the values for the text :");
String S;
Scanner scn = new Scanner(System.in);
if ((S = scn.next())!= null) {
text += S.split("\\|");
}
scn.close();
}
public String toString() {
Settext();
String S = "the output of document class toString method is " + text;
return S;
}
答案 0 :(得分:0)
使用此代替if语句 -
int noOfNulls = 0;
while(noOfNulls != 2)
{
if ((S = scn.next()) != null)
{
text += S.split("\\|");
noOfNulls = 0;
}
else
noOfNulls++;
}
答案 1 :(得分:0)
我认为这可能会对你有所帮助。你描述的是什么考虑到用户可能会多次按Enter键但不能连续按下。
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
String buffer="";
boolean previusEnter=false;
while(readString!=null) {
if (readString.equals("")){
if(previusEnter)
break;
previusEnter=true;
}
else
previusEnter=false;
buffer+= readString+"\n";
if (scanner.hasNextLine())
readString = scanner.nextLine();
else
readString = null;
}