我必须将infix操作转换为后缀操作,但是infix操作必须输入为每行一个字符。因此,不需要输入这样的内容: 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发布于 2018-11-05 05:00:43
你没有具体说明这是一项学校作业,或者你有一定的限制,所以这个答案无可否认是暗箱操作。
我建议在循环中使用StringBuilder,读取nextLine()而不是简单的next()。这允许您确定条目是否为空(即:按下enter键而没有输入字符)。
此外,我们应该允许用户输入多个字符(当他们尝试输入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);
}这能满足你的需要吗?
发布于 2018-11-05 05:09:56
这应该能做你想做的。仅仅读第一个角色就有其局限性。
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;
}https://stackoverflow.com/questions/53148470
复制相似问题