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();
}
}
I'm trying to display the output of an AVL Tree inorder, preorder, and postorder traversals on multiple lines in the JTextArea, preferably 10 numbers to a line. I tried the 'for' loop I've provided, but I'm getting a compile error. The problem is with inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal));.
Error:
AVLTree.java:527: error: no suitable method found for toString(String) inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal)); ^ method StringBuilder.toString() is not applicable (actual and formal argument lists differ in length) method AbstractStringBuilder.toString() is not applicable (actual and formal argument lists differ in length) method Object.toString() is not applicable (actual and formal argument lists differ in length) 1 error
How can I re-write this line of code to make it work? Thank you for all your help.
Related
So I refactored a Linear Search code that only uses the main method. My goal is to convert it into an OOP approach. But I have trouble saving the input set of integers.
// LinearSearchDriver.java
import java.util.Scanner;
public class LinearSearchDriver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinearSearch linearSearch = new LinearSearch();
System.out.println("Enter number of elements");
int numElements = in.nextInt();
linearSearch.setNumberOfElements(numElements);
System.out.println("Enter " + numElements + " integers");
for (int count = 0; count < numElements; count++){
int setIntegers = in.nextInt();
linearSearch.setNumberOfIntegers(setIntegers);
}
System.out.println("Enter value to find");
int search = in.nextInt();
linearSearch.findValue(search);
}
}
//LinearSearch.java
public class LinearSearch {
private int c;
private int n;
private int array[];
public void setNumberOfElements(int n) {
this.n = n;
this.array = new int[n];
}
public void setNumberOfIntegers(int y) {
for (c=0; c < n; c++)
array[c] = y;
}
public void findValue(int search) {
for (c = 0; c < n; c++) {
if (array[c] == search) { /* Searching element is present */
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) { /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
}
Example output:
But when I input number 1, this is the output:
The program only reads number 2 output which I think, the last number is only the one that is saving to an array.
for (c = 0; c < n; c++) {
array[c] = y;
}
is where things go wrong. You're setting the last value passed to that function for every index in the Array.
You can adress this in several ways:
Pass an Array to the function instead of a single argument.
You can determine the current number of elements in your Array and then append the newest value "manually". See this post.
Or you could simply use a dynamic structure, such as a List and append the element to that.
Here is a rough outline for the 3rd Option:
public class LinearSearch {
private List<Integer> intList;
public LinearSearch() {
}
public void setNumberOfElements(int n) {
intList = new ArrayList<>(n); //Set the capacity here like before.
}
public void setNumberOfIntegers(int y) {
//If you want your List to always only contain the initially allowed number of elements, you could implement
// this logic here, by adding the new value and removing the "oldest" one.
intList.add(y);
}
public void findValue(int search) {
if (!intList.contains(search)) { //You can put this up here and potentially skip the looping.
System.out.println(search + " is not present in array.");
return;
}
for (int n : intList) {
if (n == search) {
System.out.println(search + " is present at location " + intList.indexOf(search) + ".");
return; //Use return to exit the method, break only exits the loop in your example, and you could print both lines.
}
}
}
}
I made a main method, insertion sort and want it to print out properly in my tester class. I know that it cannot print because its a void method using arrays and I need it to be a string to print, I'm just not sure what to edit in my method or my print line to make it feasible.
METHOD
public static void insertionSort(String[] inputList)
{
OrderStrings c = new OrderStrings();
for (int i = 1; i < inputList.length; i++)
{
String index = inputList[i];
int j = i;
while ( j > 0 && c.compare((sort(inputList[j])), sort(inputList[j-1])) > 0)
{
inputList[j] = inputList[j-1];
j--;
}
inputList[j] = index;
}
}
TESTER
#Test
public void testInsertionSort()
{
AnagramUtil insertionTest = new AnagramUtil();
String[] test2 = { "ComputerScience" };
System.out.print("Testing Insertion Sort");
System.out.println();
System.out.println(insertionTest.insertionSort("sorted" + test2);
//the above is the line that will not print
//it says "- The method insertionSort(String[]) in the type AnagramUtil is not applicable for the arguments(String)"
}
I have a programming assignment for an introductory level Java class (the subset sum problem) - for some reason, my recursive method isn't executing properly (it just goes straight to the end of the method and prints out the sorted list). Any help would be appreciated - I'm a newbie and recursive functions are really confusing to me.
package programmingassignment3;
import java.io.*;
import java.util.*;
public class ProgrammingAssignment3 {
static int TARGET = 10;
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
public static void main(String[] args) {
populateSortSet();
sumInt(list);
recursiveSS(list);
}//main
public static void populateSortSet() {
try {
File f = new File("set0.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !list.contains(ele)) {
list.add(ele);
}//if
}//while
Collections.sort(list);
}//try
catch (IOException e) {
e.printStackTrace();
}//catch
}//populateSet
public static void recursiveSS(ArrayList<Integer> Alist) {
if (Alist.size() == SIZE) {
if (sumInt(Alist) == TARGET) {
System.out.println("The integers that equal " + TARGET + "are: " + Alist);
} //if==TARGET
}//if==SIZE
else {
for (int i = 0; i < SIZE; i++) {
ArrayList<Integer> list1 = new ArrayList<>(Alist);
ArrayList<Integer> list0 = new ArrayList<>(Alist);
list1.add(1);
list0.add(0);
if (sumInt(list0) < TARGET) {
recursiveSS(list0);
}//if
if (sumInt(list1) < TARGET) {
recursiveSS(list1);
}//if
}//for
}//else
System.out.println("echo" + Alist);
}//recursiveSS
public static int sumInt(ArrayList<Integer> Alist) {
int sum = 0;
for (int i = 0; i < SIZE - 1; i++) {
sum += Alist.get(i);
}//for
if (Alist.size() == TARGET) {
sum += Alist.get(Alist.size() - 1);
}//if
return sum;
}//sumInt
}//class
This thing that you do at class level:
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
means that SIZE will be initiated to 0, and stay 0 (even if you add elements to the list.)
This means that the code inside the for-loop will be executed 0 times.
Try something like:
public class ProgrammingAssignment3 {
private static int initialSize;
//...
public static void populateSortSet() {
//populate the list
initialSize = list.size();
}
So you don't set the value of the size variable until the list is actually populated.
That being said, there a quite a few other strange things in your code, so I think you need to specify exactly what you are trying to solve here.
Here's how I'd do it. I hope it clarifies the stopping condition and the recursion. As you can see, static methods are not an issue:
import java.util.ArrayList;
import java.util.List;
/**
* Demo of recursion
* User: mduffy
* Date: 10/3/2014
* Time: 10:56 AM
* #link http://stackoverflow.com/questions/26179574/recursive-method-not-properly-executing?noredirect=1#comment41047653_26179574
*/
public class RecursionDemo {
public static void main(String[] args) {
List<Integer> values = new ArrayList<Integer>();
for (String arg : args) {
values.add(Integer.valueOf(arg));
}
System.out.println(String.format("input values : %s", values));
System.out.println(String.format("iterative sum: %d", getSumUsingIteration(values)));
System.out.println(String.format("recursive sum: %d", getSumUsingRecursion(values)));
}
public static int getSumUsingIteration(List<Integer> values) {
int sum = 0;
if (values != null) {
for (int value : values) {
sum += value;
}
}
return sum;
}
public static int getSumUsingRecursion(List<Integer> values) {
if ((values == null) || (values.size() == 0)) {
return 0;
} else {
if (values.size() == 1) { // This is the stopping condition
return values.get(0);
} else {
return values.get(0) + getSumUsingRecursion(values.subList(1, values.size())); // Here is recursion
}
}
}
}
Here is the case I used to test it:
input values : [1, 2, 3, 4, 5, 6]
iterative sum: 21
recursive sum: 21
Process finished with exit code 0
Thanks everyone. I really appreciate the help. I did figure out the problem and the solution is as follows (closing brace comments removed for the reading pleasure of #duffymo ):
public class ProgrammingAssignment3 {
static int TARGET = 6233;
static ArrayList<Integer> set = new ArrayList<>();
static int SIZE;
static int count = 0;
public static void populateSortSet() {
try {
File f = new File("set3.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !set.contains(ele)) {
set.add(ele);
}
}
Collections.sort(set);
SIZE = set.size();
System.out.println("The original sorted set: " + set + "\t subset sum = " + TARGET);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void recursiveSS(ArrayList<Integer> list) {
if (list.size() == SIZE) {
if (sumInt(list) == TARGET) {
System.out.print("The Bit subset is: " + list + "\t");
System.out.println("The subset is: " + getSubset(list));
count++;
}
}
else {
ArrayList<Integer> list1 = new ArrayList<>(list);//instantiate list1
ArrayList<Integer> list0 = new ArrayList<>(list);//instantiate list0
list1.add(1);
list0.add(0);
if (sumInt(list0) <= TARGET) {
recursiveSS(list0);
}
if (sumInt(list1) <= TARGET) {
recursiveSS(list1);
}
}
}
public static int sumInt(ArrayList<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
sum += set.get(i);
}
}
return sum;
}
public static ArrayList<Integer> getSubset(ArrayList<Integer> list) {
ArrayList<Integer> l = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
l.add(set.get(i));
}
}
return l;
}
}
I am new to programming and don't get why the program gives me a run time error for NullPointerException when I have tried initializing n, numInt, and arrayMenu. None of which seem to work. The program's job is to gather a set of random integers to store in an array and allow the user to pick which sort to choose from. Thanks for reading.
import java.util.Scanner;
import java.util.Random;
public class VariousSortsHS
{
private static int[] arrayMenu;
private static Random generator;
/**
* Constructor for objects of class VariousSortsHS.
*/
public VariousSortsHS(int n) //The error starts here
{
arrayMenu = new int[n]; //I don't get why it says null in the array when
//i am initializing the length of the array to n
/*Assigns a random number between 0 too 100.*/
for(int i = 0; i < n; i++)
{
int temp = generator.nextInt(100);
arrayMenu[n] = temp;
}
}
/**
* Selection Sort method.
*/
public static void selection(int n)
{
for(int i = 0; i < arrayMenu.length - 1; i++)
{
int minPos = i;
for(int j = i + 1; j < arrayMenu.length; j++)
{
if(arrayMenu[j] < arrayMenu[minPos]) minPos = j;
}
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[minPos];
arrayMenu[minPos] = temp;
System.out.print(temp + " ");
}
}
/**
* Insertion Sort method.
*/
public static void insertion(int n)
{
for(int i = 1; i < arrayMenu.length; i++)
{
int next = arrayMenu[i];
int j = i;
while(j > 0 && arrayMenu[j - 1] > next)
{
arrayMenu[j] = arrayMenu[j - 1];
j--;
}
arrayMenu[j] = next;
System.out.print(next + " ");
}
}
/**
* Quick Sort method.
*/
public static void quick(int n)
{
int pivot = arrayMenu[0];
int i = 0 - 1;
int j = n + 1;
while(i < j)
{
i++; while(arrayMenu[i] < pivot) i++;
j++; while(arrayMenu[j] > pivot) j++;
if(i < j)
{
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[j];
arrayMenu[j] = temp;
System.out.print(temp + " ");
}
}
}
/**
* Main method that allows user to input data.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you wish to sort random integers? (Yes or No) ");
String answer = in.next();
String answer2 = answer.toLowerCase();
do
{
/*Prompts for array length.*/
System.out.println("How many random integers do you wish to sort?");
int numInt = in.nextInt();
/*Promps for sort selection choice.*/
System.out.println("Select a sort to use: \n\t1)Selection\n\t2)Insertion\n\t3)Quick");
String sort = in.next();
String sort2 = sort.toLowerCase();
if(sort2.equals("selection"))
{
selection(numInt);
}
else if(sort2.equals("insertion"))
{
insertion(numInt);
}
else if(sort2.equals("quick"))
{
quick(numInt);
}
else
{
System.out.println("You have entered the wrong input.");
}
} while(!answer2.equals("no"));
}
}
Everything in your code is static. This means the constructor you wrote is never called, and the array has never been changed from its default value, null. Consider changing your constructor code to a static initialization block instead.
generator is never set to anything, so it's null too and you can't call nextInt on it
initializing the array is setting arrayMenu[n] instead of arrayMenu[i]
When you call insertion(numInt);, method public static void insertion(int n) is called and then you are trying to do the for-loop like this for(int i = 1; i < arrayMenu.length; i++)
However, arrayMenu was not initialized, it is null. When you try to call a length, on null, you get NullPointerException.
You need to add a static constructor and initialize the size using a static int
//set parameter = n
public static int parameter;
static
{
arrayMenu = new int[parameter];
}
I am trying to implement a generic selection sort which can take any objects and do the sorting on it. I can promise to the compiler that whatever objects I am comparing, has the compareTo method implemented for it. But I get compile error for the following code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SelectionSortGenerics implements Comparable<E> {
private <E> void swap(E[] a, int i, int j) {
if (i != j) {
E temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public <E> void selectionSort(E[] a) {
for (int i = 0; i < a.length - 1; i++) {
// find index of smallest element
int smallest = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j].compareTo(a[smallest])<=0) {
smallest = j;
}
}
swap(a, i, smallest); // swap smallest to front
}
}
public static void main(String[] args){
SelectionSortGenerics firstsort = new SelectionSortGenerics();
Integer[] arr = {3,4,1,5};
System.out.println("before sorting int: "+ Arrays.toString(arr));
firstsort.selectionSort(arr);
System.out.println("After sorting int : "+Arrays.toString(arr));
String[] arr1= {"acd","ded","dal","bad","cle"};
System.out.println("before sorting String: "+ Arrays.toString(arr1));
firstsort.selectionSort(arr1);
System.out.println("After sorting String : "+Arrays.toString(arr1));
Character[] arr2= {'c','e','a','d','c'};
System.out.println("before sorting char: "+ Arrays.toString(arr2));
firstsort.selectionSort(arr2);
System.out.println("After sorting char : "+Arrays.toString(arr2));
}
}
As you can see, the objects I am passing in main method are Integer, String and Character, which has compareTo methods. how would make the above code work. Anywhere, casting is needed?
Thanks for your help.
The following works for me. All I did was remove the <E> in the class declaration and changed <E> to <E extends Comparable<E>> in selectionSort.
The generic <E> in the class declaration is unnecessary and potentially confusing since your class doesn't actually need to be generic. Only the methods in the class are generic, not the class itself.
Second, the selectionSort method requires the element type passed in to be comparable to itself. You can represent this by E extends Comparable<E>.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SelectionSortGenerics {
private <E> void swap(E[] a, int i, int j) {
if (i != j) {
E temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public <E extends Comparable<E>> void selectionSort(E[] a) {
for (int i = 0; i < a.length - 1; i++) {
// find index of smallest element
int smallest = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j].compareTo(a[smallest])<=0) {
smallest = j;
}
}
swap(a, i, smallest); // swap smallest to front
}
}
public static void main(String[] args){
SelectionSortGenerics firstsort = new SelectionSortGenerics();
Integer[] arr = {3,4,1,5};
System.out.println("before sorting int: "+ Arrays.toString(arr));
firstsort.selectionSort(arr);
System.out.println("After sorting int : "+Arrays.toString(arr));
String[] arr1= {"acd","ded","dal","bad","cle"};
System.out.println("before sorting String: "+ Arrays.toString(arr1));
firstsort.selectionSort(arr1);
System.out.println("After sorting String : "+Arrays.toString(arr1));
Character[] arr2= {'c','e','a','d','c'};
System.out.println("before sorting char: "+ Arrays.toString(arr2));
firstsort.selectionSort(arr2);
System.out.println("After sorting char : "+Arrays.toString(arr2));
}
}
**Refer below method to implement generic sorting.You just have to pass list in sortElements and the name of the field on you want to enable sorting**
/**
* This method is used to sort the elements based on the fieldName specified.
* Sorting order is Ascending order.
*
* #param resultList
* e.g., List of ProductBrand
* #param fieldName
* e.g., productBrandName list will be sorted according to this
* fieldName.
* #throws Exception
*/
public static <Type> void sortElements(List<Type> resultList, final String fieldName, final boolean isDesc) throws Exception
{
Collections. sort(resultList, new Comparator<Type>()
{
#Override
public int compare(Type o1, Type o2)
{
return compareValue(o1, o2);
}
private int compareValue(Type o1, Type o2)
{
int returnValue = 0;
try
{
Field field = o1.getClass().getDeclaredField(fieldName);
boolean accessible = field.isAccessible();
field.setAccessible( true);
Object objectO1 = field.get(o1);
Object objectO2 = field.get(o2);
if (objectO1 instanceof Number)
{
if ((objectO1 != null && objectO2 != null)
&& (objectO1 instanceof Integer || objectO1 instanceof Long || objectO1 instanceof Byte))
{
returnValue = Long.valueOf(objectO1 + "").compareTo(Long. valueOf(objectO2 + ""));
}
else if ((objectO1 != null && objectO2 != null) && (objectO1 instanceof Double || objectO1 instanceof Float))
{
returnValue = Double.valueOf(objectO1 + "").compareTo(Double. valueOf(objectO2 + ""));
}
}
else if (objectO1 instanceof String || objectO1 instanceof Character)
{
if ((objectO1 != null) && objectO2 != null)
{
returnValue = normalizedString(String.valueOf(objectO1)).compareToIgnoreCase(
normalizedString(String.valueOf(objectO2)));
}
}
field.setAccessible(accessible);
}
catch (Exception e)
{
System. out.println("Error occured while sorting elements");
}
if (isDesc)
{
if (returnValue > 0)
{
return -1;
}
else if (returnValue < 0)
{
return 1;
}
}
return returnValue;
}
});
}
/**
* This methods Normalizes the input string. Here we remove accent from the
* character so that we can sort the string properly using normal characters.
*
* #param str
* example <B> BSH Electrodom�sticos Espa�a S.A. </b>
* #return Normalized String . <B> ex : BSH Electrodomesticos Espana S.A.</b>
*
*/
public static String normalizedString(String str)
{
if (!isNullOrBlank(str))
{
String nfdNormalizedString = Normalizer. normalize(str, Normalizer.Form.NFD );
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return pattern.matcher(nfdNormalizedString).replaceAll("");
}
else
{
return "" ;
}
}
/**
* This function checks that the value is blank or null.
*
* #param value
* value to be checked
* #return true if value is blank or null
*/
public static boolean isNullOrBlank(String value)
{
boolean retFlag = false;
if (value == null || value.trim().equals("") || value.trim().equals("null" ))
{
retFlag = true;
}
return retFlag;
}
Note: The sorting algorithm implemented below works only for an array of the length of a power of two. You can use this technique for other sorting algorithms too:
Approach 1: Using java.util.Comparator
Approach 2:Using T extends Comparable
Main Method:Main method