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;
}
添加回答
舉報
