亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 (input == '\n') 之類的東西來確定何時停止接受用戶輸入?

如何使用 (input == '\n') 之類的東西來確定何時停止接受用戶輸入?

Smart貓小萌 2021-12-30 16:46:52
我必須將中綴操作轉換為后綴操作,但是中綴操作必須作為每行一個字符輸入。因此,不是輸入這樣的東西:3-2,你需要輸入這樣的東西:3-2我有一個想法,使用 =='\n' 來確定輸入的字符是否是下一行函數,以便確定等式的結尾,但它不起作用。我嘗試用不同的字符替換它,例如 =='e',并且效果很好。我能做些什么來解決這個問題?   String string = "";   Scanner input = new Scanner(System.in);   boolean flag = true;   while (flag==true)   {       char charIn = input.next().charAt(0);       string = string + charIn;       if (charIn=='e') //inputting 'e' gives me my desired result       {           flag = false;       }   }   //code that passes string to InfixToPostfix method and prints out the answer. this part works fine
查看完整描述

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);

}

這是否滿足您的需求?


查看完整回答
反對 回復 2021-12-30
?
侃侃爾雅

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;

}


查看完整回答
反對 回復 2021-12-30
  • 2 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號