java - 从左到右而不是从右到左扫描字符串计算总数
问题描述
我基本上是想找出一种可以从左到右扫描字符串的技术,它会给我它的整数。从右到左开始很容易,如下面的代码所示。我只是在努力寻找一种方法来添加每个整数以使其成为应有的正确值。
输出:你想输入一个表达式吗?y 输入表达式 2567 value = 7652
我试图让输出的顺序正确。
e = String input // string needing to be converted to double
p = 0 // position
// If a substring of e whose rightmost character is at position p
// represents a number (possibly with a decimal point, possibly negative),
// return the numerical value of the substring as a double value and
// re-position p just to the left of the substring.
private double formNum() {
double total = 0.0;
int count = 0;
int flag = 0;
double mult = 1;
char c, d;
do {
c = e.charAt(p); // examine the current character in the string (from right to left)
if (c == '.') {
flag = 1; // set a flag to remember that the character is a decimal point
} else {
// if the current character is a digit, convert to its
// int value and include it in the value corresponding to the string.
if ((c >= '0') && (c <= '9')) {
total = total + mult * (c - '0');
mult = mult * 10.0;
if (flag == 0) {
count++; // count the number of digits to the right of a possible decimal point
}
} else {
if (c == '(' && e.charAt(p + 1) == '-') {
total = -total; // an underscore character represents a negative value
}
}
}
p++; // Prepare to move to the next character to the left.
// This is a private non-static method because it changes the member variable p
d = '?';
if (p <= e.length() - 1) {
d = e.charAt(p); // the next character to the left
}
} while ((p <= e.length() - 1) && (((d <= '9') && (d >= '0')) || (d == '_') || (d == '.')));// check for a valid
// character
if (flag == 1) {
total = total / Math.pow(10, count * 1.0); // compute the value taking into account
// the number of decimal places
}
return total;
}
解决方案
推荐阅读
- python - 尝试构建 BeautifulSoup 以灵活地抓取公司年报
- flutter - 在 setState 中使用异步操作的解决方法
- c++ - c++14 - 如何在 Windows 中使用独立的 libcurl 库启用 HTTPs
- firebase - Firestore 不必要地保存重复条目
- powershell - 为什么 adb exec-out 在 powershell 中的行为不同?
- angular - 在 Angular HttpHeaders 中将对象作为参数传递
- authentication - 创建身份验证系统
- c++ - 共享指针时删除指针向量的父级是否安全?
- firebase - 保持 Firestore 写入的原子性对于批处理操作来说太大(>500)
- python - 如何使用范围不等式向 pyomo 添加约束