首页 > 解决方案 > 如何定义此变量以使其不会读取错误?

问题描述

前几天开始学习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++;
        }
    }
}

标签: java

解决方案


您可以使用以下代码:

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; }

推荐阅读