如何使用 (input == '\n') 之类的东西来确定何时停止接受用户输入?

我必须将中缀操作转换为后缀操作,但是中缀操作必须作为每行一个字符输入。因此,不是输入这样的东西: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


Smart猫小萌
浏览 142回答 2
2回答

千巷猫影

您没有说明这是学校作业或您有某些限制,因此这个答案无可否认是在黑暗中进行的。我建议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);}这是否满足您的需求?

侃侃尔雅

这应该做你想做的。仅读取第一个字符有其局限性。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;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java