2012-11-02 40 views
-5

我试过下面 http://mynotes.wordpress.com/2009/07/23/java-generating-random-string/随机文本[已解决]

我努力去适应了代码为我使用本网站的代码。生成以下结果

get方法不起作用。这里是我的代码:

/* 
* Retorna nomes e sobrenomes 
*/ 
package gamification; 

import java.util.Random; 

public class Textos { 

    /* 
    * http://mynotes.wordpress.com/2009/07/23/java-generating-random-string/ 
    */ 
    public static char[] alphanumeric = alphanumeric(); 
    public static Random rnd = new Random(); 

// public CRUD() {this(null);} 
// public CRUD(Random rand) {this.rand = (rand != null) ? rand : new Random();} 
    public static String getTexto(int len) { 
     StringBuffer out = new StringBuffer(); 

     while (out.length() < len) { 
      int idx = Math.abs((rnd.nextInt() % alphanumeric.length)); 
      out.append(alphanumeric[idx]); 
     } 
     return out.toString(); 
    } 

    // create alphanumeric char array 
    private static char[] alphanumeric() { 
     StringBuffer buf = new StringBuffer(128); 
     for (int i = 48; i <= 57; i++) { 
      buf.append((char) i); // 0-9 
     } 
     for (int i = 65; i <= 90; i++) { 
      buf.append((char) i); // A-Z 
     } 
     for (int i = 97; i <= 122; i++) { 
      buf.append((char) i); // a-z 
     } 
     return buf.toString().toCharArray(); 
    } 

    // Metodo que gera n registros aleatorios 
    public static void gerarRegistrosAleatorios(ArrayList lista, int n) 
      throws ParseException { 
     final long intervalo = 1000000000; 
     for (int i = 0; i < n; i++) { 
      Usuario u = new Usuario(proximoID(lista)); 

      Random rnd = new Random(); 
      String nomeComposto = Textos.getNomes()[rnd.nextInt(Textos.getNomes().length)] 
        + " " + Textos.getSobrenomes()[rnd.nextInt(Textos.getSobrenomes().length)]; 
      u.nome = nomeComposto; 
      u.pontos = rnd.nextInt(3000); 

      u.perguntas = new ArrayList<Pergunta>(); 
      for (int j = 0; j < rnd.nextInt(10); j++) { 
       Pergunta p = new Pergunta(); 
       p.Pergunta = Textos.getTexto(15); 

       p.resposta = new ArrayList<Resposta>(); 
       for (int k = 0; k < rnd.nextInt(5); k++) { 
        Resposta r = new Resposta(); 
        r.Resposta = Textos.getTexto(20); 
        p.resposta.add(r); 
       } 
       u.perguntas.add(p); 
      } 

      calcularEmblemas(u); 

      // para dataP usar exemplo de prest\exercicios\random04DiferencaDataVetor 
      // Vetores usados para receber os valores de getNewData 
      int vE[]; 
      int vS[]; 
      do { 
       vE = getNewData(); 
       vS = getNewData(); 
      } while (vS[0] < vE[0]); 

      /* 
      * Transforma os dados numa String para atribuir aos campos 
      * horaEntrada e horaSaida. No caso, foi considerado uma diferenca 
      * apenas nas horas e minutos, dia, mes e ano sao os mesmos. hh:mm 
      * dd/MM/yyyy 
      */ 
      String dateStringE = vE[0] + ":" + vE[1] + " " + vE[2] + "/" + vE[3] + "/" + vE[4]; 
      String dateStringS = vS[0] + ":" + vS[1] + " " + vE[2] + "/" + vE[3] + "/" + vE[4]; 
      u.horaEntrada = dateStringE; 
      u.horaSaida = dateStringS; 
      lista.add(u); 
     } 
    } 

我的代码更完整。

+1

最新错误? – PermGenError

+1

'get(int len)'方法无法工作?我们甚至无法考虑如何解决它,而不知道它是如何工作的,以及它是如何工作的。 – Vulcan

+0

我在代码中看不到明显的错误。也许如果你告诉我们出了什么问题,我们会知道该找什么。 – Jay

回答

1

此行不会编译

u.perguntas.Pergunta = rnd.get(10); 

这是错误的Java代码。它应该像

//assuming this is the code you need 
u.perguntas.Pergunta pergunta = new Pergunta(rnd.nextInt(10)); 

或者,也许你与你的CRUD#get方法混淆了Random#next。如果是这种情况下,代码应该被重构,以类似

CRUD crud = new CRUD(); 
//using the Random#nextInt that returns a value between 0 and 9 
//sending that value to the CRUD#get method 
u.perguntas.Pergunta pergunta = new Pergunta(crud.get(rnd.nextInt(10))); 

或许

CRUD crud = new CRUD(); 
//sending 10 to the CRUD#get method 
u.perguntas.Pergunta pergunta = new Pergunta(crud.get(10); 

正如我所说的,那些都只是从你的实际代码的推测。


通过重新阅读类的代码,有很多问题有:

  • 定义你的方法的范围:公共,私有,保护,默认。
  • 误解staticnon-static方法。
  • 使用未初始化的变量。
  • 使用static方法中的对象属性和方法。

看起来您对Java编程概念有严重的疑问。您的代码应该是这样的:

import java.util.ArrayList; 
import java.util.Random; 
import java.util.Scanner; 

public class CRUD { 

    public char[] alphanumeric = alphanumeric(); 
    public Random rnd; 

    // Metodo que gera n registros aleatorios 
    //This method should be public in order to be used in classes 
    //outside the class package 
    public static void gerarRegistrosAleatorios(ArrayList lista, int n) { 
     for (int i = 0; i < n; i++) { 
      Usuario u = new Usuario(proximoID(lista)); 
      //you're shadowing the Random rnd attribute of the class 
      //that explain why this line works 
      Random rnd = new Random(); 
      String nomeComposto = Textos.getNomes()[rnd.nextInt(Textos.getNomes().length)] 
        + " " + Textos.getNomes()[rnd.nextInt(Textos.getNomes().length)]; 
      u.nome = nomeComposto; 
      u.pontos = (int) Math.round(Math.random() * 5000); 
      // not work the next line 
      //this is bad Java code 
      //u.perguntas.Pergunta = rnd.get(10); 
      //trying to fix your code 
      u.perguntas.Pergunta pergunta = new u.perguntas.Pergunta(); 
      lista.add(u); 
     } 
    } 

    /* 
    * http://mynotes.wordpress.com/2009/07/23/java-generating-random-string/ 
    */ 

    //by default, if you don't define any constructor, the compiler 
    //will create a public constructor with no arguments nor code for you 
// public CRUD() { 
//  this(null); 
// } 
// 
// public CRUD(Random rand) { 
//  this.rand = (rand != null) ? rand : new Random(); 
// } 

    //this method won't run well 
    //and you can't use it in a `static` method like gerarRegistrosAleatorios 
    //Here you use rnd. This is the attribute of the class (not the rnd in the 
    //gerarRegistrosAleatorios method) and it's initialized by default with null value. 
    public String get(int len) { 
     StringBuffer out = new StringBuffer(); 
     //initializing rnd 
     rnd = new Random(); 
     while (out.length() < len) { 
      int idx = Math.abs((rnd.nextInt() % alphanumeric.length)); 
      out.append(alphanumeric[idx]); 
     } 
     return out.toString(); 
    } 

    // create alphanumeric char array 
    private char[] alphanumeric() { 
     StringBuffer buf = new StringBuffer(128); 
     for (int i = 48; i <= 57; i++) { 
      buf.append((char) i); // 0-9 
     } 
     for (int i = 65; i <= 90; i++) { 
      buf.append((char) i); // A-Z 
     } 
     for (int i = 97; i <= 122; i++) { 
      buf.append((char) i); // a-z 
     } 
     return buf.toString().toCharArray(); 
    } 
} 

基于最新补丁,如果你想使用CRUD#get方法在CRUD#gerarRegistrosAleatorios方法,你必须做下列之一:

  1. 关闭get方法和Random rnd变量变为static。如果你这样做,请记住在声明时初始化rnd静态变量,而不是在get方法中。
  2. gerarRegistrosAleatorios方法中删除static修饰符。但是这样做,你将不得不创造任何你想要的CRUD类的新实例/需要调用这个方法:

    CRUD crud = new CRUD(); 
    crud.gerarRegistrosAleatorios(...); //set the parameters of the method... 
    

有将被创建内一个新的CRUD实例的第三条道路gerarRegistrosAleatorios方法(如答案的第一位),但您选择的解决方案将严重依赖于您的课程设计。

+0

这也行不通。据我所知,'Random'没有'get(int)'方法。 – NullUserException

+0

它也没有公共的'next(int)'方法。你的意思是使用['nextInt(int)'](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29)? – Vulcan

+0

@LuiggiMendoza是的,我看到了。我可以'明白为什么你需要在那里创建一个新的'CRUD'。 – NullUserException