正在使用变量?

时间:2015-02-02 03:50:23

标签: java variables

我已经在同一个问题上看到了一些线索,所以如果我错过了对某些内容的阅读,我会非常抱歉,但这个问题真让我讨厌。所以我在这里有这个代码:

int megaBytes = 0;
int megaByteSpeed = 0;
int totalSeconds = 0;
int secondsRemainder = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
Scanner sc = new Scanner(System.in);

if (megaBytes < 1000)
    {
        totalSeconds = megaBytes / megaByteSpeed;
        hours = totalSeconds / 3600;
        secondsRemainder = totalSeconds % 3600;
        minutes = secondsRemainder / seconds;
        seconds = minutes % 60;
    }

我知道我的编码可能有点错误,但我是Java的新手,我开始有点心慌。 我得到的错误是说变量; megaByteSpeedtotalSecondssecondsRemainder未被使用。这显然属于数学部分。有谁知道为什么会发生这种情况?这导致我的项目停止运行。

感谢您提供任何信息, Scuire。

整个代码:

public class Ch03_ex3_DownloadTime {
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) 
  {
    System.out.println("Welcome to the Download Time Estimator!");
    System.out.println();

    int megaBytes = 0;
    int megaByteSpeed = 0;
    int totalSeconds = 0;
    int secondsRemainder = 0;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;
    Scanner sc = new Scanner(System.in);

    while (megaBytes != 1000)
    {
      System.out.print("Enter download size: ");
      megaBytes = sc.nextInt();

      System.out.print("Enter download speed: ");
      megaByteSpeed = sc.nextInt();

      if (megaBytes < 1000)
      {
        totalSeconds = megaBytes / megaByteSpeed;
        hours = totalSeconds / 3600;
        secondsRemainder = totalSeconds % 3600;
        minutes = secondsRemainder / seconds;
        seconds = minutes % 60;
      }
      String message = "\n" 
                   +  "This download will take approximately " + hours + "hours" + minutes + "minutes and " + seconds + "seconds";
      System.out.println(message);
    }
  }
}

1 个答案:

答案 0 :(得分:3)

首先让我给你一个提示:按照网站关于如何发布代码的说明。

现在,从我的代码中可以看出,我看到你除以0 这里:

    minutes = secondsRemainder / seconds; 

这里是您需要更改以停止循环的部分

    boolean quit = false;
    while (!quit)
    {
        System.out.print("Enter download size: ");
        megaBytes = sc.nextInt();

        System.out.print("Enter download speed: ");
        megaByteSpeed = sc.nextInt();

    if (megaBytes < 1000)
        {
            totalSeconds = megaBytes / megaByteSpeed;
            hours = totalSeconds / 3600;
            secondsRemainder = totalSeconds % 3600;
            minutes = secondsRemainder / seconds;
            seconds = minutes % 60;

        }
        String message = "\n" 
                       +  "This download will take approximately " + hours + "hours" + minutes + "minutes and " + seconds + "seconds";
        System.out.println(message);

        System.out.println("Do you want to continue 1= yes 0 = no");
        int ans  = 0;
        ans = sc.nextInt();
        if(ans ==0){
            quit = true;
        }
    }