首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何使用(输入== '\n')之类的东西来确定何时停止接受用户输入?

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

Stack Overflow用户
提问于 2018-11-05 04:43:54
回答 2查看 54关注 0票数 0

我必须将infix操作转换为后缀操作,但是infix操作必须输入为每行一个字符。因此,不需要输入这样的内容: 3-2,您需要输入如下内容:

代码语言:javascript
复制
3
-
2

我有一个想法,使用=='\n‘来确定输入的字符是否是下一行函数,从而确定方程的结尾,但它不起作用。我试着用一个不同的字符(如=‘e’)来代替它,而且效果很好。我能做些什么来解决这个问题?

代码语言:javascript
复制
   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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-05 05:00:43

你没有具体说明这是一项学校作业,或者你有一定的限制,所以这个答案无可否认是暗箱操作。

我建议在循环中使用StringBuilder,读取nextLine()而不是简单的next()。这允许您确定条目是否为空(即:按下enter键而没有输入字符)。

此外,我们应该允许用户输入多个字符(当他们尝试输入22作为一个数字时会发生什么)。放弃char类型允许这样做。

代码语言:javascript
复制
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);
}

这能满足你的需要吗?

票数 1
EN

Stack Overflow用户

发布于 2018-11-05 05:09:56

这应该能做你想做的。仅仅读第一个角色就有其局限性。

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53148470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档