java - 如何定义此变量以使其不会读取错误?
问题描述
前几天开始学习java,我可能只是定义错误的变量。在下面的脚本中,变量 x 在编译期间显示“未找到符号错误”。我已经尝试更改变量名称,在代码头部定义它,并检查我所有的大括号。有人可以告诉我有什么问题吗?
编码:
public class covidSim {
static void main(String[] args) {
int currentDay=0;
int currentCases=1;
int targetDay=100;
while(currentDay < targetDay) {
int exeNum = currentCases;
System.out.println("Day|");
while(exeNum > 0) {
int randomSpread = (int)(Math.random() * 9);
if (randomSpread > 0 && randomSpread < 5) {
int x = 0;
}
if (randomSpread > 4) {
int x = (int)(Math.random() * 5);
}
exeNum--;
currentCases = currentCases + x;
}
System.out.println(currentCases);
System.out.println(currentDay);
currentDay++;
}
}
}
解决方案
您可以使用以下代码:
int exeNum = currentCases;
while(exeNum > 0) {
int randomSpread = (int)(Math.random() * 9);
int x = 0;
if (randomSpread > 4) {
x = (int)(Math.random() * 5);
}
exeNum--;
currentCases = currentCases + x;
}
您不再需要指定此条件,因为 x 仅在以下情况下更改为不同的值randomSpread > 4
:
if (randomSpread > 0 && randomSpread < 5) {
int x = 0; }
推荐阅读
- jquery - Jquery 开始损坏
- c# - 自本月初以来计算数据库行数
- ios - 如何使 UICollectionView 的高度可自动调整和滚动?
- python - 点聚类算法
- graphics - 将 Maya 导出的 OBJ 文件转换为三角形网格 OFF 文件 -- AssertionError: face should have 3 vertices but has 6
- javascript - 使复选框所需的输入文本相乘
- php - 从 PHP 5 升级到 7。创建的数组只有 null 值,然后才创建一个空数组
- android - 使用 fstream 读取文件然后关闭并再次读取将无法在 Android 上运行
- c# - 无法访问 HTML 文档中的特定元素(使用 HTML Agility)
- python - 如果没有 Django 中的“parent.attrib”语法,子类如何访问其父属性?