I am using
i=sscanf(input,"%f %c %f",&operand1,operator,&operand2);
in C for parsing the input which is of the format
operand1 operator operand2
operator can be + - * / ^
operand +
or -
any double
is there any method similar in JAVA
a convenient option is to use the java.util.Scanner
-class. The following code snippet should get you going to parse inputs:
import java.util.Scanner;
public class ScannerExample {
public static void main(String args[]) {
// Declare variables
Scanner s;
float f1;
float f2;
char op;
// Ask for input data
System.out.println("Enter Data: ");
// Initialize a Scanner-object using stdin
s = new Scanner(System.in);
// Read and parse the data
f1 = s.nextFloat();
op = s.next().charAt(0);
f2 = s.nextFloat();
System.out.println(f1 + " " + op + " " + f1);
// Closes the scanner
s.close();
}
}
Error checking was omitted for the sake of brevity.
Edit: As @electricchef pointed out, one could also use the useDelimiter(Pattern pattern)
-function of Scanner
as an alternative approach, like so:
s = new Scanner(System.in);
s.useDelimiter("\\s+");
f1 = s.nextFloat();
op = s.next().charAt(0);
f2 = s.nextFloat();
Here, the input is splitted at one or more whitespace-characters as it is denoted by the regex-pattern "\\s+"
.
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.