I need to be able to read in user input and break it apart for later use. The user can input whole or fractional numbers and an operation, and I'm not sure how to read this in.
An example of user input is 4/8 – 3/12
or 3 + 2/3
or 12/16 * 4
or -2/3 / 64/96
.
Right now I'm using something like this:
public class FractionApp
{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int[] fraction = new int[5];
String input;
String operation;
System.out.println("Enter the expression: ");
input = s.next();
StringTokenizer st = new StringTokenizer (input, "/" + " ");
fraction[0] = Integer.parseInt(st.nextToken());
fraction[1] = Integer.parseInt(st.nextToken());
operation = st.nextToken();
fraction[2] = Integer.parseInt(st.nextToken());
fraction[3] = Integer.parseInt(st.nextToken());
}
}
Should be reading the user input as Tim Bender suggested with
nextLine();
. Then obliviously once you've retrieved theinput
you'll need to pre process the data withSplit
inorder to seperate the information gathered, before doing any computation.I think the easiest way to figure out the contents of each
input
would be match it against aregular expression
. Otherwise you could also try with a a large set ofif conditions
or with agrammar parser
(but it is tedious).Try
Scanner.nextLine
this will read in to the point when the user pressed "enter". Though it leaves you to split the returned String through your own parsing methods. Sort of defeats the advantages of usingScanner
.Implement the power of regular expressions.
You should use
Scanner.nextLine()
to get the full line that was input into the console. Manipulate theString
after you read in the line from theScanner
.Trial run:
Input:
1.5+4.2*(5+2)/10-4
Output:
[1.5, +, 4.2, *, (, 5, +, 2, ), /, 10, -, 4]