Java 学习避免使用静态方法/变量。在创建返回数字的非静态方法时遇到问题
我想尝试在不需要的时候避免使用静态方法/变量,因为我听说/看到/听到有人告诉我,如果可以的话,你希望避免使用它们。我决定用Java制作一个简单的密码破解程序:Java 学习避免使用静态方法/变量。在创建返回数字的非静态方法时遇到问题,java,oop,static,Java,Oop,Static,我想尝试在不需要的时候避免使用静态方法/变量,因为我听说/看到/听到有人告诉我,如果可以的话,你希望避免使用它们。我决定用Java制作一个简单的密码破解程序: import java.util.Random; public class PasswordCracker { public static void main(String args[]) { PasswordCracker pwcSimulation = new PasswordCracke
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;
}
}
import java.util.Random;
公共类密码破解器
{
公共静态void main(字符串参数[])
{
PasswordCracker pwcSimulation=新的PasswordCracker();
长期总时间=0;
整数模拟=100;
对于(int i=0;i 对于(inti=0;iNo),您做的每件事都是正确的
您将返回破解该密码所需的时间(以毫秒为单位)
答案小于1毫秒。您看到0了吗?这是因为您的方法返回0。这样做是因为endTime-startTime
为零
只需编写return 1
自己测试一下,您就会看到打印循环打印1。提示:对于基准测试,请使用而不是System.currentTimeMillis
。计算经过的时间。例如:Duration.ofNanos(System.nanoTime()-start)
您的问题是什么?