我已经看到了关于同一问题的一些帖子,所以如果我错过了阅读某些内容,我深表歉意,但这个问题真的很烦我。所以我这里有这段代码:
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 新手,我开始变得有点慌乱。
我收到的错误是变量; megaByteSpeed
、totalSeconds
和 secondsRemainder
未使用。很明显,它们在数学部分是这样的。有谁知道为什么会发生这种情况?这导致我的项目在运行中停止。
感谢您提供任何信息, 斯奎尔.
整个代码:
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);
}
}
}
最佳答案
首先让我给您一个提示:按照网站上有关如何发布代码的说明进行操作。
现在,从你的代码中我可以看出你正在除以 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;
}
}
关于java - 正在使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270845/