[英]Parsing the Data in java
I am using我在用
i=sscanf(input,"%f %c %f",&operand1,operator,&operand2);
in C for parsing the input which is of the format在 C 中用于解析格式的输入
operand1 operator operand2
operator can be + - * / ^
运算符可以是
+ - * / ^
operand +
or -
any double操作数
+
或-
任何双精度
is there any method similar in JAVA JAVA中是否有类似的方法
a convenient option is to use the java.util.Scanner
-class.一个方便的选择是使用
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:编辑:正如@electricchef 指出的那样,也可以使用
Scanner
的useDelimiter(Pattern pattern)
作为一种替代方法,如下所示:
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+"
.在这里,输入被拆分为一个或多个空白字符,如正则表达式模式
"\\s+"
所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.