我是Java和Android Studio的初学者。我做了一个(有点复杂)的计算器,可以计算分数,整数以及混合分数。它的工作原理是先将输入的数字(无论采用哪种格式)转换为分数,然后进行计算。这是代码的一部分:
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fraction_1 = editTextNum1.getText().toString();
String fraction_2 = editTextNum2.getText().toString();
int Num1, Den1, Num2, Den2;
if (fraction_1.contains("/") && !fraction_1.contains(" ")){
Num1 = Integer.parseInt(getFraction(fraction_1)[0]);
Den1 = Integer.parseInt(getFraction(fraction_1)[1]);
} else if (fraction_1.contains(" ") && fraction_1.contains("/")){
int[] frac1 = convertFromMixed(fraction_1);
Num1 = frac1[0];
Den1 = frac1[1];
}
else if (!fraction_1.contains("/")) {
Num1 = Integer.parseInt(fraction_1);
Den1 = 1;
}
else{
invalidinput invalidinput = new invalidinput();
invalidinput.show(getSupportFragmentManager(), "num1error");
}
if (fraction_2.contains("/") && !fraction_2.contains(" ")){
Num2 = Integer.parseInt(getFraction(fraction_2)[0]);
Den2 = Integer.parseInt(getFraction(fraction_2)[1]);
} else if (fraction_2.contains(" ") && fraction_2.contains("/")){
int[] frac2 = convertFromMixed(fraction_1);
Num2 = frac2[0];
Den2 = frac2[1];
}
else if (!fraction_2.contains("/")){
Num2 = Integer.parseInt(fraction_2);
Den2 = 1;
} else{
invalidinput invalidinput = new invalidinput();
invalidinput.show(getSupportFragmentManager(), "num2error");
}
int commonDen = getLCM(Den1, Den2);
Num1 = (commonDen/Den1)*Num1;
Num2 = (commonDen/Den2)*Num2;
int addNum = Num1 + Num2;
if (simplify.isChecked()){
String result = simplify(addNum, commonDen);
result = checkFor1(result);
result = checkForWhole(result);
textViewResult.setText(result);
} else {
String result = addNum + "/" + commonDen;
result = checkFor1(result);
textViewResult.setText(result);
}
}
});
在最后一部分,计算commonDen时出现错误。它表示尚未初始化Num1,Num2,Den1和Den2。 这只是附加部分。这些变量用于计算时,都会出现错误。请帮忙。
答案 0 :(得分:2)
因此您必须初始化变量。您可以通过
改变
int Num1, Den1, Num2, Den2;
到
int Num1 = 0, Den1 = 0, Num2 = 0, Den2 = 0;