public class AVLTree
{
public static String inorderTraversal = " ";
private static void inorder(AVLNode btree)
{
if (btree != null)
{
inorder(btree.left);
inorderTraversal += btree.value + " ";
inorder(btree.right);
}
}
/**
This inorder method is the public interface to
the private inorder method. It calls the private
inorder method and passes it the root of the tree.
*/
public static void inorder()
{
inorder(root);
}
}
class AVLTreeDemo extends JFrame
implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
String cmdStr = cmdTextField.getText();
int size = Integer.parseInt(cmdStr);
int[] array = new int[size];
// input validation
// Random number method
randNum(array, size);
// for loop adds numbers to AVL Tree
for (int i = 0; i < size; i++)
{
int value = array[i];
avlTree.add(value);
}
if (view != null)
remove(view);
view = avlTree.getView();
add(view);
pack();
validate();
cmdResultTextField.setText(" ");
// inorder method
AVLTree.inorder();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++)
{
sb.append(String.format(" %2d", size)); // Formats right justified
if ((i + 1) % 10 == 0)
{
sb.append(System.lineSeparator()); // Adds a new line after 10 values
}
}
//inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal));
// display the array in inorder to the inorder text field
inorderTextArea.setText(AVLTree.inorderTraversal);
}
/**
The randNum method randomly selects numbers
in a given range.
@param array The array.
@param num The integer numbers.
*/
public static void randNum(int[] array, int num)
{
Random rand = new Random();
// Selection sort method
selectionSort(array);
// display duplicates
/*int last = array[0];
int count = -1;
for (int i : array)
{
if (i == last)
{
count++;
continue;
}
System.out.println("Number " + last + " found " + count + " times.");
count = 1;
last = i;
}*/
for(int i = 0; i < num; i++)
{
// display duplicates
/*if(num == num - 1)
{
System.out.print("Duplicate: " + num);
}*/
array[i] = rand.nextInt(500);
}
}
public static void main(String [ ] args)
{
AVLTreeDemo atd = new AVLTreeDemo();
}
}
我正在尝试在JTextArea
中的多行上显示AVL树的顺序,预订和后序遍历的输出,最好是10行到一行。我尝试了我提供的'for'循环,但是我遇到了编译错误。问题出在inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal));
。
错误:
AVLTree.java:527:错误:没有为toString(String)找到合适的方法inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal)); ^方法StringBuilder.toString()不适用(实际和形式参数列表长度不同)方法AbstractStringBuilder.toString()不适用(实际和形式参数列表长度不同)方法Object.toString()不适用(实际和形式参数列表的长度不同)1错误
如何重新编写这行代码才能使其正常工作?谢谢你的帮助。