I have to convert an infix operation to a postfix one, however the infix operation must be inputted as one character per line. So instead of inputting something like this: 3-2, you would need to input something like this:
3
-
2
I had an idea of using =='\\n' to determine whether the inputted character is a next line function so that would determine the end of the equation, but it doesn't work. I tried replacing it with a different character such as =='e', and that works perfectly. What can I do to fix this?
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
You did not specify that this was a school assignment or that you had certain restrictions, so this answer is admittedly a shot in the dark.
I would recommend using a StringBuilder
within a loop and reading nextLine()
instead of simply next()
. This allows you to determine if the entry was empty (ie: the enter key was pressed without entering a character).
Also, we should allow the user to enter more than one character anyway (what happens when they try to enter 22
as a number). Abandoning the char
type allows for this.
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);
}
Does this meet your needs?
This should do what you want. Reading just the first character has its limitations.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.