How to make a Linear Search OOP approach that uses Input Scanner - java

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.
}
}
}
}

Related

I want to search a specific element of an array and if it exists to return its index

I have created an array of type Savings which contains a String (Name) and a double (Account Number). I want to search using an Account Number and see if it exist and then return all the elements (Name + Account Number) and the Index of the Array that contain these elements. I tried this but it does not work.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Savings[] ArrayOfSavings = new Savings[5];
System.out.print("Enter Account Number: ");
Scanner scan = new Scanner(System.in);
double Ms = scan.nextDouble();
//Loop until the length of the array
for(int index = 0; index<= ArrayOfSavings.length;index++){
if(ArrayOfSavings[index].equals(Ms)){
//Print the index of the string on an array
System.out.println("Found on index "+index);
}
}
ArrayOfSavings[0] = new Savings("Giorgos",87654321);
ArrayOfSavings[1] = new Savings("Panos",33667850);
}
}
/Savings Class/
public class Savings extends Generic {
public Savings(String FN, double AN) {
super(FN, AN);
}
#Override
public String toString(){
return String.format("Customer: %s \n Acount Number: %.1f,
getFirstName(),getAccNumber();
}
}
You could do something like this, where you return -1 if it doesn't exist, or the index if you've found it. Just have to make sure you check for this case.
public static int findSavingsIfExists(double accountNumber, Savings[] allSavings) {
for(int i = 0; i < allSavings.length(); i++) {
if(allSavings[i].accountNumber == accountNumber) {
return i;
}
}
return -1;
}
and use it like so
int index = findSavingsIfExists(..., ArrayOfSavings);
if(index != -1) {
Savings foundSavings = ArrayOfSavings[index];
} else {
//Not found
}
Try to use somethig like this:
double Ms = scan.nextDouble();
int index = 0;
for (int i = 0; i < ArrayOfSavings.length; i++) {
if (ArrayOfSavings[i].getAccountNumber == Ms ) {
index = i;
break;
}
}
System.out.println(index);

AVL Tree traversals in JTextArea

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.

Code stops working about 1/5 the way on specific sets of data

We had to write a sorting algorithm ourselves. I wrote one, it works for 20-5000 data sets of integer, finishes in about 4 milliseconds. However, when I moved on to the 25000 data set, it stopped working at numbers with value 804; I have been trying to figure out why for the past 2 days and have no luck, my teacher tried his hand at it for 5 minutes and gave up. Any ideas as to why it would just get stuck on an infinite loop on the same number would be very much appreciated!
Edit: Commented inner loop
Edit 2: Added full code
Here is the code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
public class sort_old
{
static long steps=0;
static int nums, temp;
static int[] numbers, sorted, usedNum;
static String path="20_source.txt";
static Scanner scan;
static boolean used;
public static void main()
{
try
{
scan = new Scanner(new File(path));
while(scan.hasNextInt())
{
nums++;
scan.nextInt();
}
numbers= new int[nums];
sorted = new int[nums];
usedNum = new int[nums];
scan.close();
scan = new Scanner (new File(path));
try
{
for(int x = 0; x < nums; x++)
{
numbers[x]=scan.nextInt();
}
}
catch(NoSuchElementException e)
{
}
scan.close();
sortLargestToSmallest();
System.out.println(checkResults(sorted,true));
}
catch(FileNotFoundException e)
{
System.out.println("Sucks to suck");
}
}
private static void sortLargestToSmallest()
{
int counter=nums-1; // mums is the number of numbers in the data set.
for(int y = 0; y < nums; y ++)
{
temp = num[0]; //num[] is the array containing all the numbers
used=false; //boolean to for checking if the number was used already
for(int x = 0; x < nums; x ++)
{
if(temp<=num[x]) //finding the largest number
{
for(int j = 0; j < y; j++) //only check up to the numbers already assigned
{
if(usedNum[j]==x) //see if the number is already used. usedNum[] stores indexes of numbers already used; compare to current index
{
used=true; //the number is already sorted, so it moves on to the next
break;
}
else
used=false;
step++;
}
if(!used)//only if the number is not already sorted is it changed to temp
{
temp=num[x];
usedNum[y]=x;
}
}
}
sorted[counter]=temp; //putting the sorted value into the sorted array
counter--; // we were asked to sort from smallest to largest, but for some reason it didn't work.
}
}
}
public static boolean checkResults (int[] theArray, boolean report)
{
System.out.println("Checking Validity");
boolean stillValid = true;
int counter = 0;
while (stillValid && counter < theArray.length - 1)
{
if (theArray[counter] > theArray[counter + 1])
{
stillValid = false;
}
counter++;
}
if (report)
{
if (stillValid)
{
System.out.println("Checked " + theArray.length + " values. Sort is valid");
}
else
{
System.out.println("Checked " + theArray.length + " values. Found error at " + counter);
}
}
return stillValid;
}
}

Java Why am I getting a NullPointerException while instantiating my array

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];
}

Java sorting text file with Comparable

I need a program that reads in data and sorts the file in descending order using quicksort based on the index provided for instance this is the data using comparable
adviser,32/60,125,256,6000,256,16,128,198,199
amdahl,470v/7,29,8000,32000,32,8,32,269,253
amdahl,470v/7a,29,8000,32000,32,8,32,220,253
amdahl,470v/7b,29,8000,32000,32,8,32,172,253
amdahl,470v/7c,29,8000,16000,32,8,16,132,132
And i need to sort by the 5th index(mmax) case 2 and the 6th(cache) case 3 and the ninth index(php) case 4 in descending order & print the first index which is already sorted case 1
The problems with my code are as follows:
It doesn't sort based off the index
It gives me an error at runtime with the code: Arrays.sort(c);
Please help with suggestions
Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Prog4 {
static Scanner input;
static File filename;
/**
* This function displays the menu for the user to choose an option from
*/
public void menu() {
System.out.println("Option 1: Sort by VENDOR: ");
System.out.println("Option 2: Sort decreasing number by MMAX: ");
System.out.println("Option 3: Sort decreasing number by CACH: ");
System.out.println("Option 4: Sort decreasing number by PRP: ");
System.out.println("Option 5: Quit program");
}
/**
* Constructor to handle the cases in the menu options
* #throws FileNotFoundException
* #throws IOException
*/
public Prog4() throws FileNotFoundException {
//Accepts user input
Scanner in = new Scanner(System.in);
//calls the menu method
menu();
//Initializes the run variable making the program loop until the user terminates the program
Boolean run = true;
//While loop
while (run) {
switch (in.nextInt()) {
case 1:
System.out.println("Option 1 selected");
System.out.println("Sorted by vendor:");
filename = new File("machine.txt");
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Instantiate a new Array of String type
String array [] = new String[10];
//while it has next ..
while (input.hasNext()) {
//Initialize variable
int i = 0;
//store each word read in array and use variable to move across array array[i] = input.next();
//print
System.out.println(array[i]);
//so we increment so we can store in the next array index
i++;
}
case 2:
System.out.println("Press any key to continue");
Scanner input2 = new Scanner(System.in);
String x = input2.nextLine();
if (x.equals(0)) continue;
System.out.println("Option 2 selected") ;
Computer[] c = new Computer[10];
filename = new File("machine.txt");
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Arrays.sort(c);
while (input.hasNextLine()) {
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
}
}
}
/**
* Main method
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
//Calls the constructor
new Prog4();
//static Scanner input;
}
public static void quickSort(int arr[], int left, int right) {
if (left < right) {
int q = partition(arr, left, right);
quickSort(arr, left, q);
quickSort(arr, q+1, right);
}
}
private static int partition(int arr[], int left, int right) {
int x = arr[left];
int i = left - 1;
int j = right + 1;
while (true) {
i++;
while (i < right && arr[i] < x)
i++;
j--;
while (j > left && arr[j] > x)
j--;
if (i < j)
swap(arr, i, j);
else
return j;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Comparator class:
import java.util.Comparator;
class Computer implements Comparable<Computer> {
private String vendor;
private int mmax;
private int cach;
private int php;
public Computer(int value) {
this.mmax = value;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getMmax() {
return mmax;
}
public void setMmax(int mmax) {
this.mmax = mmax;
}
public int getCach() {
return cach;
}
public void setCach(int cach) {
this.cach = cach;
}
public int getPhp() {
return php;
}
public void setPhp(int php){
this.php = php;
}
#Override
public int compareTo(Computer m) {
if (mmax < m.mmax) {
return -1;
}
if (mmax > m.mmax) {
return 1;
}
// only sort by height if age is equal
if (cach > m.cach) {
return -1;
}
if (cach < m.cach) {
return 1;
}
if (php > m.php) {
return -1;
}
if (php < m.php) {
return 1;
}
return 0;
}
public static Comparator<Computer> ComparemMax = new Comparator<Computer>() {
#Override
public int compare(Computer p1, Computer p2) {
return p2.getMmax() - p1.getMmax();
}
};
}
The biggest problem is that the Computer classes do not get instantiated for each line that gets read.
As you want to have different sort options depending on the user input, you can not let the Computer class determine the compare method, but instead you will need to create a separate Comparator implementation for each sort option. Next, make the file read operation generic and abstract it away in a separate method call from each selected case. Instead of an array of Computers, I would make it a List or a Set, because you don't (want to) know the length up front.
I would like to lay out the steps in detail so that you could figure out each step for yourself. You have got a lot of it right.. but there are gaps.
Create a Computer class. It should have a constructor which takes a single String and splits it using the separator ',' and parses each part to String/int as applicable. (It would be preferable for you to parse and store the whole string.. which means you can have 10 fields in your class)
Create a blank ArrayList to store the Computer objects.
Iterate through the file and readLine
Call the Computer constructor using the String representing each line in the file within the while loop
Add the new Computer object to the computers ArrayList
Write 5 different comparators.
Based on user input, instantiate the correct comparator and pass it to the sort method
Print the sorted array
If you still face a problem, mention the specific point at which you like more clarity..

Categories