2 回答
TA贡献1829条经验 获得超7个赞
您没有说明这是学校作业或您有某些限制,因此这个答案无可否认是在黑暗中进行的。
我建议StringBuilder在循环中使用 a并阅读nextLine()而不是简单的next(). 这允许您确定条目是否为空(即:在没有输入字符的情况下按下了回车键)。
此外,我们应该允许用户输入多个字符(当他们尝试输入22数字时会发生什么)。放弃char类型允许这样做。
public static void main(String[] args) {
StringBuilder string = new StringBuilder();
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag) {
// Capture all characters entered, including numbers with multiple digits
String in = input.nextLine();
// If no characters were entered, then the [ENTER] key was pressed
if (in.isEmpty()) {
// User is done adding characters; exit the loop
flag = false;
} else {
// Otherwise, get the text entered and add it to our final string
string.append(in);
}
}
System.out.println("Final String: " + string);
}
这是否满足您的需求?
TA贡献1801条经验 获得超16个赞
这应该做你想做的。仅读取第一个字符有其局限性。
String string = "";
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag==true)
{
String nextLine = input.nextLine();
char charIn;
if(nextLine.length() > 0) {
charIn = nextLine.charAt(0); //This is bad idea as you can only operate on single digit numbers
System.out.println("charIn = " + charIn);;
string = string + charIn;
}
else
flag = false;
}
添加回答
举报
