samedi 16 juillet 2016

How to input random numbers into a binary search tree using Java?

So whilst attempting to code a binary search tree of my own, I've run into a small problem. What I've tried to do is, firstly, generate random numbers (based on the user's input) and then insert those numbers into the tree and then return the tree.

Here is my code for the random number generator:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
//RANDOM NUMBER GENERATOR
public class RandomIntGenerator {
public static List<Integer> RandIntGen(){

Scanner s = new Scanner(System.in);
System.out.println("Enter the number of nodes for the tree: ");
int reps = s.nextInt(); 
s.close();

List <Integer> RandInts = new ArrayList<Integer>();
Random r = new Random();

for(int i = 0; i<reps ;i++) {
    int value = r.nextInt(100);
    RandInts.add(value);    
}
return RandInts;
}
}

And the tree:

public class BST {
public static Node root;
public BST(){
this.root = null;
}
//declaring variables

class Node{
int data;
Node left;
Node right;
public Node(int data){
    this.data = data;
    left = null;
    right = null;
}
}
public void insert(int x){
Node newNode = new Node(x);
if(root==null){
    root = newNode;
    return;
}
Node current = root;
Node parent = null;
while(true){
    parent = current;
    if(x<current.data){
        current = current.left;
    if(current == null){
        parent.left = newNode;
    return;
    } else{
        current = current.right;
        if(current==null){
            parent.right = newNode;
            return;
        }
    }
    }
}
}
public void display (Node root){
if (root!=null){
    display(root.left);
    System.out.println(" "+ root.data);;
    display(root.right);
}
}

public static void main(String[] args){
BST b = new BST();
int counter = RandomIntGenerator.RandIntGen().size();
for (int i=0; i<counter; i++){
    int num = (RandomIntGenerator.RandIntGen().get(i));
    b.insert(num);
}
System.out.println("Tree is: ");
b.display(b.root);
}
}

And then when I run it it gives me this:

Enter the number of nodes for the tree: 
12
Enter the number of nodes for the tree: 
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at RandomIntGenerator.RandIntGen(RandomIntGenerator.java:15)
at BST.main(BST.java:55)

So really my question is two-fold, why does it give me these errors and how can I fix it?




Aucun commentaire:

Enregistrer un commentaire