简体   繁体   English

Java从字符串中提取多个值

[英]Java Extract multiple values from String

As part of a calulator program I am writing, I am required to have the user input all the parameters in one string and I need to extract the corresponding values from it. 作为我正在编写的计算器程序的一部分,我需要让用户在一个字符串中输入所有参数,并且需要从中提取相应的值。

For example the user enters "3 5 *" he'll get "15" back. 例如,用户输入“ 3 5 *”,他将得到“ 15”。

So the program I need to write will take '3' and assign that to double input1 , '5' to double input2 , and '*' to char operator . 因此,我需要编写的程序将使用'3'并将其分配给double input1 ,将'5'分配给double input2 ,并将'*'分配给char operator How do I get java to assign parts of a string to different members. 如何获取java将字符串的一部分分配给不同的成员。

I was thinking of maybe splitting the user's string into multiple strings and parsing the values out but I don't know how effective that would be. 我当时正在考虑将用户的字符串拆分为多个字符串并解析出值,但我不知道这样做的效果如何。 Thanks in advance. 提前致谢。

You will need to consider the order of operations if you have more then one operation. 如果要执行多个操作,则需要考虑操作的顺序。 IE (3 4 +) 3 *. IE(3 4 +)3 *。 A common method for this would be to use a stack. 常见的方法是使用堆栈。 Push the values onto the stack and perform the operation on the values you pop following the operation itself. 将这些值压入堆栈,然后按照操作本身对弹出的值进行操作。 For parsing simply split on the space ' '. 为了解析,只需在空格“”上分割。 However if you have more complex expressions consider a post order traversal, or stack implementation. 但是,如果您有更复杂的表达式,请考虑使用后顺序遍历或堆栈实现。

This question has already been answered here: Evaluating a math expression given in string form 这里已经回答了这个问题:计算以字符串形式给出的数学表达式

I gave a very simple breakdown in my answer here as well: Calculating String-inputed numerical expressions? 我在这里的回答中也给出了一个非常简单的细分: 计算字符串输入的数字表达式?

You can use the StringTokenizer to split the string wherever it finds a space. 您可以使用StringTokenizer在任何找到空格的地方拆分字符串。

String s = "3 5 *"; 字符串s =“ 3 5 *”; StringTokenizer st = new StringTokenizer(s); StringTokenizer st =新的StringTokenizer(s);

You can check if there are more tokens via st.hasMoreTokens(). 您可以通过st.hasMoreTokens()检查是否有更多令牌。 You can use the token aka string via st.nextToken() (it returns a string). 您可以通过st.nextToken()使用令牌aka字符串(它返回一个字符串)。

You can also cast each "string" such as the "3" into a double via: String firstNumString = "3"; 您还可以通过以下方式将每个“字符串”(例如“ 3”)转换为双精度型:String firstNumString =“ 3”; Double first = Double.parseDouble(firstNumString); 双第一= Double.parseDouble(firstNumString);

This results in the Double variable 'first' containing the number 3. 这将导致Double变量“ first”包含数字3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM