我尝试生成随机代码名称作为 licenseKey 并检查它是否存在于数据库中。如果不存在,则显示在我的jsp页面中,如果存在,则继续生成随机代码。我收到错误“java.lang.StackOverflowError”。如何解决这个问题?下面是我的代码:
package com.raydar.hospital;
import com.raydar.hospital.DB_Connection;
import java.sql.*;
public class RandomCodeGenerator {
String licenseKey = "";
int noOfCAPSAlpha = 4;
int noOfDigits = 4;
int minLen = 8;
int maxLen = 8;
char[] code = RandomCode.generateCode(minLen, maxLen, noOfCAPSAlpha, noOfDigits);
public RandomCodeGenerator(){
}
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
System.out.println("4 + " +result);
if (result=="false"){
System.out.println("1 + " +new String(code));
licenseKey = new String(code);
}
else if (result=="true"){
System.out.println("2 + " +new String(code));
licenseKey = new String(code);
isLicenseKeyExist ();
}
return licenseKey;
}
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
String result="";
System.out.println("3 + " +code);
try{
DB_Connection connect = new DB_Connection();
connection = connect.getDBConnection();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT licenseKey FROM hospital WHERE licenseKey = '" +code+ "'");
if (rs.next()){
result = "true";
}
else{
result = "false";
}
}catch (Exception e){
System.out.println("Error retrieving data! "+e);
}
return result;
}
最佳答案
您创建一个递归循环,其中 isLicenseKeyExist() 调用 getOutputCode(),然后 getOutputCode() 调用 isLicenseKeyExist()。所以最终你用完了堆栈空间,并得到这个异常。
这里,
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
...
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
...
}
关于java - 如何生成随机码并检查它是否存在于数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22600345/