[英]Learning to avoid using static methods/variables. having trouble making a non-static method that returns a number
I want to try practicing avoiding using static methods/variables when not needed, because I've heard/seen/been told that you want to avoid using them when you can.我想尝试在不需要时避免使用 static 方法/变量,因为我听说/看到/被告知您想尽可能避免使用它们。 I decided to make a simple password cracker in Java:
我决定在 Java 中做一个简单的密码破解器:
import java.util.Random;
public class PasswordCracker
{
public static void main(String args[])
{
PasswordCracker pwcSimulation = new PasswordCracker();
long totalTimeSpentCracking = 0;
int numSimulations = 100;
for(int i = 0; i < numSimulations; i++)
{
System.out.println(pwcSimulation.PasswordCrackingSimulation());
}
}
long PasswordCrackingSimulation()
{
long startTime = System.currentTimeMillis();
int upperBound = 999999;
Random rand = new Random();
int randomPassword = rand.nextInt(upperBound);
int passwordGuess;
for(int i = 0; i <= upperBound; i++)
{
passwordGuess = i;
if(passwordGuess == randomPassword)
{
System.out.println("password Guessed correctly, the password was: " + randomPassword);
break;
}
/*else
{
System.out.println("Your inputted password is incorrect, please try again.");
}*/
}
long endTime = System.currentTimeMillis();
long timeSpentCracking = (endTime - startTime);
System.out.println("The program took " + timeSpentCracking + "ms OR ~" + ((timeSpentCracking/1000) % 60) + " seconds to complete");
return timeSpentCracking;
}
}
first instantiated a new class (hopefully i did this they way you should ?) to avoid having to use a static method for the method PasswordCrackingSimulation.首先实例化一个新的 class(希望我按照他们应该的方式这样做?)以避免必须对 PasswordCrackingSimulation 方法使用 static 方法。 Now i'm having trouble returning a value from the method.
现在我无法从该方法返回一个值。 The printline in the loop will always print 0, so I know that it isn't taking the returned value in the method.
循环中的 printline 将始终打印 0,因此我知道它没有采用方法中的返回值。 Any help would be lovely:) just trying to learn
任何帮助都会很可爱:)只是想学习
No, you're doing everything correctly.不,你做的一切都是正确的。
You're returning how long it takes in milliseconds to crack that password.您将返回破解该密码所需的毫秒数。
The answer is less than 1 millisecond.答案不到 1 毫秒。 That 0 you see?
你看到那个0? That's because your method is returning 0. It is doing that because
endTime - startTime
is zero .那是因为您的方法返回 0。这样做是因为
endTime - startTime
为零。
Just write return 1
to test this out yourself - you'll see your print loop print 1 instead.只需编写
return 1
来自己测试一下 - 你会看到你的打印循环 print 1 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.