DaniCV Posted March 17, 2015 at 11:06 PM Report Share #579667 Posted March 17, 2015 at 11:06 PM Boa noite a todos, Preciso aqui de uma ajuda para fazer um código que não sei o que fazer mesmo 😞 A ideia até que é simples: Ir buscar uma lista de nomes a um documento txt e depois fazer com que o programa pegue em dois alunos aleatórios e forme grupos. E depois voltar a escrever um ficheiro (isso wu até tenho uma ideia de como fazer). O meu problema é fazer com que ele remove um determinado número do "random" para que não se volte a repetir. O resto até tenho uma ideia. import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.Random; import java.util.Scanner; public class Extra { public static void main(String[] args) { Scanner leitor = new Scanner(System.in); System.out.print("Introduza o nome do ficheiro:"); String fileName = leitor.nextLine(); File f = new File(fileName + ".txt"); int contador = 0, i = 0; try { Random r = new Random(); leitor = new Scanner(f); while (leitor.hasNext()) { leitor.nextLine(); contador++; } String[] lista = new String[contador]; leitor = new Scanner(f); while (leitor.hasNext()) { lista[i] = leitor.nextLine(); i++; int k = r.nextInt(lista.length); int l = r.nextInt(lista.length); } } catch (FileNotFoundException e) { System.out.println("O ficheiro não existe!"); } } } Se poderem ajudar agradecia tenho de entregar isto até sexta feira e já não sei o que fazer. Grato. Link to comment Share on other sites More sharing options...
bioshock Posted March 18, 2015 at 10:13 AM Report Share #579691 Posted March 18, 2015 at 10:13 AM Se percebi o teu problema, estás com dúvidas em não repetir o número dos grupos? Se sim, tens duas formas: a primeira é guardar numa lista os números dos grupos que já estão em uso; a segunda é verificar no ficheiro onde guardas. O código pode não funcionar na perfeição porque não tenho forma de o testar, mas fica a lógica. public class Extra { private static List<Integer> groups = new ArrayList<Integer>(); public static void main(String[] args) { // .... int k = groupNumber(length); // Significa que o grupo já existe if(k == 0) { while(k == 0) { // Gera um novo número k = groupNumber(length); } } } private static int groupNumber(int length) { Random r = new Random(); int value = r.nextInt(length); // Grupo já existe.. if(groups.contains(value)) { return 0; } groups.add(value); return value; } } Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now