为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 (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 关注
  • 141 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号