[英]Adding and Subtracting numbers from a String
該程序接收一個字符串,並將所有整數加起來,我已將定界符設置為“ +”,並由任意數量的空格包圍。 它可以正常工作,但是現在我希望它也可以使用任何負整數,例如,如果我輸入“ 8 + 33 + 1,345-37”; 輸出為41,甚至沒有達到1,345或從總數中減去-37。 分隔符是否“已跳過”? 例如,如果我說編譯器轉到8,然后跳過“ +”,然后轉到33,是否正確? 如果我將定界符設置為“ \\ s * \\ + |-\\ s *”(嘗試+或-),則輸出仍為41,為什么?
import java.util.*;
import java.io.*;
public class Add_em_up
{
public static void main (String args [])
{
Scanner x = new Scanner (System.in);
System.out.print("Enter something like 8 + 33 + 1,345 + 137 :");
String s = x.nextLine();
Scanner sc1 = new Scanner (s);
sc1.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while (sc1.hasNextInt())
{
sc1.skip(",*");
if (sc1.hasNextInt())
{
sum = sum + sc1.nextInt();
}
}
System.out.println("Sum is: " + sum);
}
}
只需將+
, -
放在字符類中。
sc1.useDelimiter("\\s*[-+]\\s*");
如果您對使用庫Exp4j感興趣,那么這是一個簡單的解決方案。 庫將完成所有計算,您要做的就是傳遞方程式並獲得結果。
這是一個例子。
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.