在 Java 中使用扫描仪从控制台读取
Using scanner to read from console in Java
我已经尝试使用 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;
}
用这个代替你的 if 语句 -
int noOfNulls = 0;
while(noOfNulls != 2)
{
if ((S = scn.next()) != null)
{
text += S.split("\|");
noOfNulls = 0;
}
else
noOfNulls++;
}
我认为这可能对您有所帮助。做你描述的。考虑到用户可能多次按下 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;
}
我已经尝试使用 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;
}
用这个代替你的 if 语句 -
int noOfNulls = 0;
while(noOfNulls != 2)
{
if ((S = scn.next()) != null)
{
text += S.split("\|");
noOfNulls = 0;
}
else
noOfNulls++;
}
我认为这可能对您有所帮助。做你描述的。考虑到用户可能多次按下 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;
}