[英]How can i make multiple modes and that the program detects if its bimodal or trimodal
[英]How can I make a function that detects a factor in a string and converts it into a float?
在我的作業中,我的代碼必須能夠加,減,除和乘。 大多數工作是在老師的幫助下完成的,但我不知道該如何使它能夠繁殖和分裂。
我假設我需要創建一個新函數來搜索字符串中的因子,然后使其創建子字符串。
我試圖通過在第21行和第31行中添加相同的功能來擴展已經損壞的代碼,但這沒有用。
public static int resultat;
public static String stykket = "3+9-22+35*2";
public static void main (String[] args) {
while (!taltjek(stykket)){
stykket = findled(stykket);
}
if (taltjek(stykket)){
int tal = StrToInt(stykket);
stykket = "";
resultat += tal;
println(resultat);
}
}
public static String findled(String stykket){
int tal;
for(int i = stykket.length() - 1; i > 0;i--){
if ((stykket.charAt(i) =='+')||(stykket.charAt(i) == '-')||(stykket.charAt(i) == '*')) {
String strengtal = stykket.substring(i+1, stykket.length());
tal = StrToInt(strengtal);
char test = stykket.charAt(i);
switch(test){
case '+': resultat += tal;
break;
case '-': resultat -= tal;
break;
case '*': resultat *= tal;
break;
}
stykket = stykket.substring(0,i);
i = stykket.length();
}
}
return stykket;
}
public static int StrToInt(String subString) {
int resultat;
resultat = 0;
try {
resultat = Integer.valueOf(subString);
} catch (NumberFormatException e) {
println("Det der er ikke et tal");
}
return resultat;
}
public static boolean taltjek (String subString){
int resultat = 0;
try {
resultat = Integer.valueOf(subString);
} catch (NumberFormatException e) {
return false;
}
return true;
}
我期望輸出為60,但輸出為25。
該代碼從右到左評估字符串。 每當遇到運算符時,它都會解析該運算符的子字符串權限,並將該運算應用於變量“ resultat”。
resultat
尚未初始化,因此將為0
。 如果第一個運算是乘法,則它將保持為0
,因為x*0=0
。
如果我為for
循環的每個迭代打印i
和resultat
,則這是輸出(加上我的注釋)
10: 0 // input: 2 resultat = 0
9: 0 // input: *2 resultat *= 2 => 0
8: 0 // input: 5
7: 0 // input: 35
6: 35 // input: +35 resultat += 35 => 35
5: 35 // input: 2
4: 35 // input: 22
3: 13 // input: -22 resultat -= 22 => 13
2: 13 // input: 9
1: 22 // input: +9 resultat += 9 => 22
25 // in your main method: resultat += 3 => 25
所以您的代碼真正評估的是0*2+35-22+9+3
我的修復建議是:
resultat
我不知道您的代碼的要求是什么,但是恕我直言,對表達式求值器更好的方法是使用遞歸方法。 代碼更簡單(我認為),並且您可以更輕松地實現運算符優先級。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.