Just to be on the safe side I would like to point out that I do not want to evaluate an expression or a string after taking an input from the user. All I want to do is take a string input from the user and then separately print each token of the string in a separate line
Thus : if the string entered is "123 bc 76 hello +" then it would print "123", "bc", "76", "hello", "+" on each line separately.
I have written a small program where the user is asked to input an expression (a mathematical expression) and the program then prints the numbers and operators on separate lines.
For eg,
INPUT : 10 - 203 / 5
EXPECTED OUTPUT :
10
-
203
/
5
Here is the code which I wrote for the above problem :
import java.util.Scanner;
public class Sol {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String myString;
System.out.println("enter the expression : ");
myString = scanner.nextLine();
//System.out.println("your expresssion : " + myString + "\n");
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
int temp = scanner.nextInt();
System.out.println(temp);
}
else {
String operator = scanner.next();
System.out.println(operator);
}
}
}
}
I felt that the problem is pretty straightforward and thus wrote the above code thinking my logic to be correct. However, when I run the program I do not get any output. The command line cursor just keeps blinking after taking the input and there is no response/output etc.
Also, while this is happening, when I input something again (in the running process) and if it a single token like for eg a string token or integr token, then it gets printed.
That is, if I enter 10 + 203 / 55 and hit enter the program keeps the blinking cursor. There is no output. Now, if at this point I enter a single token like for example "20" or "/" or "abc" then that thing gets printed and the loop continues. The program does not end!
I actually have to press ctrl + z to quit execution!!
Could anyone please tell me where I am going wrong with my program?
Also, if you could point out what needs to be done to give me the output I need, it would be of immense help!!
P.S. Actually I wrote a program to read an infix expression from a text file, covert it into postfix, evaluate it and write the result to another file. While the program worked correctly for single digit integers, it always failed for multiple digit integers. Hence I modified the code to something very similar to the above code to read 2 digit or more length integers. However, when I ran the code I got null pointer exception. That is when I decided to write the above code and check if my logic is correct or not (which it turns out is not!!).
So any help, will ultimately help me modify my infix evaluation expression accordingly.
Thanks a lot in advance!!