java - 找不到符号 - 编译错误
问题描述
所以目标是根据用户的输入计算3个月后累积的利息金额(10%)。但是,我收到了太多错误。为什么?
import java.util.Scanner;
public class showCase {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int amount = scanner.nextInt();
for(i=0; i<3; i++) {
int x = ((amount * 10) / 100);
int result = amount - x;
amount = result;
}
System.out.println(result);
}
}
./Playground/showCase.java:7: error: cannot find symbol
for(i=0; i< 3; i++) {
^
symbol: variable i
location: class showCase
./Playground/showCase.java:7: error: cannot find symbol
for(i=0; i< 3; i++) {
^
symbol: variable i
location: class showCase
./Playground/showCase.java:7: error: cannot find symbol
for(i=0; i< 3; i++) {
^
symbol: variable i
location: class showCase
./Playground/showCase.java:12: error: cannot find symbol
System.out.println(result);
^
symbol: variable result
location: class showCase
4 errors
解决方案
宣言
你忘了声明i
变量。
为此,只需在其前面加上类型。
int i = 0
// instead of just
i = 0
范围
此外,您的最终印刷品
System.out.println(result);
正在尝试使用result
循环本地的变量。所以它不再存在于循环之外。您必须在循环之前创建它:
int result = ...
for (...) {
}
System.out.println(result);
整数除法
最后,这条线不会计算你所期望的:
int x = ((amount * 10) / 100);
这里的问题是你需要整数除法,所以int / int
它也会产生一个int
,所以向下舍入。基本上1 / 3
是0
。
您必须使用浮点数,例如 a double
。
double x = ((amount * 10) / 100.0;
还要注意100.0
使它成为double
.
推荐阅读
- vagrant - 使用别名创建 Vagrant VM
- python - 我们如何在 django 的重定向函数中传递上下文字典
- mysql - 更新时添加内连接,但从第二个表中过滤
- sapui5 - 为 karma runner 设置静态路径
- javascript - 离子内容中的离子反应循环火力对象
- c++ - 当用于 c++ 中的 std::set 时,'advance()' 的运行时复杂度是多少?
- node.js - Node 和 Express - 第二次定义 app.get 不会覆盖第一次定义
- python - MDNavigationDrawer 位于阻止 MDToolBar 菜单按钮的所有内容之上
- javascript - 如何从 codepen 改变这个甜甜圈的颜色?
- javascript - Angular 字符串绑定对于 xss 预防安全吗?