In my current assignment I'm supposed to move elements between three stacks. I have one more method to write: getNumberOfMoves() and it should calculate the number of moves made between the stacks.
I want to add a calculator of some sort but the assignment says that I should write a more specific method for this. Any suggestions for how one can calculate the number of moves using a method?
Also, I'm having trouble with the method move(). I'm supposed to use push() and pop() from the other class. I did some just too see what happens, see code below, but I think I'm supposed to do it with recursion. So the base cases then should be that if the first stack 'from' only contains one element, then this should be moved directly to 'to', otherwise the last element should be moved to the 'help' stack and then to 'to'.
But, the question is, if I'm doing it recursively, shouldn't I be calling the method within the method? Then how am I supposed to use pop() and push()?
Thanks in advice!
public class StackPlay {
/**
* Returns the current number of times an element has been moved
* #return the number of moves
*/
public static long getNumberOfMoves() {
}
public static void move(myStack from,
myStack to,
myStack help,
int n) {
help.push(from.pop());
to.push(help.pop());
}
public static void main(String[] args) {
int size = 3;
myStack from = new myStack(size);
myStack to = new myStack();
myStack help = new myStack();
System.out.println("Start state");
System.out.println(" From: " + from);
System.out.println(" To: " + to);
System.out.println(" Help: " + help);
System.out.println(" Number of moves: " + getNumberOfMoves());
move(from, to, help, size);
System.out.println("End state");
System.out.println(" From: " + from);
System.out.println(" To: " + to);
System.out.println(" Help: " + help);
System.out.println(" Number of moves: " + getNumberOfMoves());
}
}
and separate class:
public class myStack {
private ArrayList<Integer> specStack;
public myStack() {
specStack = new ArrayList<Integer>();
}
public myStack(int n) {
this.specStack = new ArrayList<Integer>(n);
int i;
for (i=0; i<n; i++) {
specStack.add(i, n-i);
}
}
public void push(int x) {
if (specStack.size() == 0) {
specStack.add(x);
}
else if (x > specStack.get(specStack.size() -1)) {
throw new RuntimeException("Number too high");
}
else {
specStack.add(x);
}
}
public int pop() {
if (specStack.size() == 0) {
throw new RuntimeException("Empty stack");
}
else {
int length = specStack.size() -1;
int topEl = specStack.get(length);
specStack.remove(length);
return topEl;
}
}
public String toString() {
String arrList = "[";
int i;
for (i = 0; i < specStack.size(); i++) {
if (i == specStack.size() -1) {
arrList = arrList + specStack.get(i);
}
else {
arrList = arrList + specStack.get(i) + ",";}
}
arrList = arrList + "]";
return arrList;
}
}
Related
Good day, I have the following assignment:
https://prnt.sc/113pc7j
My problem is the first assignment of the fourth item. I prescribed filling the array with random objects, however, when I want to display this array on the screen, I get different results all the time.
My code:
The interface itself:
interface VehicleAndWorkers
{
String cars();
}
First class that implements the interface:
public class TaxiStation implements VehicleAndWorkers{
TrucksLogistic trucks = new TrucksLogistic();
public String[] cars = {"KIA", "Hyundai", "Volkswagen", "Lada", "Datsun", "Skoda"};
int quantCars = 150;
int workers = 300;
public String cars() {
System.out.println("List of models of our taxi fleet: ");
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
return null;
}
#Override
public boolean equals(Object obj)
{
return trucks.quantTrucks == this.quantCars;
}
#Override
public int hashCode() {
return Objects.hash(trucks, quantCars);
}
#Override
public String toString() {
return cars();
}
}
Second class that implements the interface:
public class TrucksLogistic implements VehicleAndWorkers {
String[] trucks = {"Kenworth W900", "Volvo FH16", "Scania R730", "MAN TGS 18.400", "МАЗ 6430",
"КАМАЗ-5490 НЕО 2"};
int quantTrucks = 40;
int workers = 100;
public String cars()
{
System.out.println("Our company model list: ");
for (int i = 0; i < trucks.length; i++)
{
System.out.println(trucks[i]);
}
System.out.println("Amount of workers: " + workers);
System.out.println("Number of trucks: " + quantTrucks);
System.out.println("The ratio of the number of truck models to the number of trucks: " +
Math.round(trucks.length / quantTrucks));
return null;
}
#Override
public String toString() {
return cars();
}
}
The class in which I tried to implement working with ArrayList (filling, displaying, etc.):
public class InterfaceArray {
ArrayList<VehicleAndWorkers> array = new ArrayList<>();
public void setArray() {
int randomLength = (int) Math.floor(random() * 10);
for (int i = 0; i < randomLength; i++) {
Random random = new Random();
int minRandomNum = 1;
int maxRandomNum = 2;
int diffRandomNum = maxRandomNum - minRandomNum;
int randomNum = random.nextInt(diffRandomNum + 1) + minRandomNum;
if (randomNum == 1) {
array.add(new TrucksLogistic() {
#Override
public String cars() {
int num = (int) Math.floor(random() * trucks.length);
quantTrucks = (int) Math.floor(random() * 100);
Random random = new Random();
int minWorkers = quantTrucks;
int maxWorkers = 200;
int diffWorkers = maxWorkers - minWorkers;
workers = random.nextInt(diffWorkers + 1);
workers += minWorkers;
System.out.println("Number of trucks: " + quantTrucks);
System.out.println("Amount of workers: " + workers);
System.out.println("Average number of workers per truck: " + Math.round(workers /
quantTrucks));
return "Priority truck brand/model: " + trucks[num];
}
});
} else {
array.add(new TaxiStation() {
#Override
public String cars() {
int num = (int) Math.floor(random() * cars.length);
quantCars = (int) Math.floor(random() * 100);
Random random = new Random();
int minWorkers = quantCars;
int maxWorkers = 200;
int diffWorkers = maxWorkers - minWorkers;
workers = random.nextInt(diffWorkers + 1);
workers += minWorkers;
System.out.println("Number of passenger cars: " + quantCars);
System.out.println("Amount of workers: " + workers);
System.out.println("Average number of employees per vehicle: " + Math.round(workers / quantCars));
return "Priority car brand/model:" + cars[num];
}
});
}
}
}
public void getArray() {
for (VehicleAndWorkers element : array) {
System.out.println("");
System.out.println(element);
System.out.println("");
}
}
public void sameElements() {
//// Set<VehicleAndWorkers> arrayTwo = new LinkedHashSet<>(array);
//// for (VehicleAndWorkers element : arrayTwo)
//// System.out.println(element + "\n");
//
// for (int element = 0; element < array.size() - 1; element++)
// {
// for (int i = element + 1; i < array.size(); element++)
// {
// if (array.get(element).equals(element + 1))
// {
// arrayTwo.add(array.get(element + 1));
// }
// }
// array.remove(array.get(element));
// }
// for (VehicleAndWorkers element : arrayTwo)
// System.out.println(element.toString());
}
public void sameTypeElements() {
ArrayList<VehicleAndWorkers> arrayTwo = new ArrayList<>();
// for (VehicleAndWorkers element : array)
// {
// if (element)
// }
}
}
Well, the class in which the methods from the previous class are applied:
public class ConsoleInterface {
void doChoice()
{
InterfaceArray interfaceArray = new InterfaceArray();
printOptions();
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
while (choice >= 0 && choice < 5) {
if (choice == 0) {
interfaceArray.setArray();
interfaceArray.getArray();
printOptions();
choice = scan.nextInt();
}
else if (choice == 1) {
interfaceArray.setArray();
printOptions();
choice = scan.nextInt();
}
else if (choice == 2) {
interfaceArray.sameElements();
printOptions();
choice = scan.nextInt();
}
else if (choice == 3) {
interfaceArray.sameTypeElements();
printOptions();
choice = scan.nextInt();
}
else if (choice == 4) {
interfaceArray.getArray();
printOptions();
choice = scan.nextInt();
}
}
}
void printOptions()
{
System.out.println("Choose an action: \n");
System.out.println("0 - Fill the array with random elements and display it on the screen. \n");
System.out.println("1 - Fill the array with random elements. \n");
System.out.println("2 - Find objects in the array,\n" +
" whose functional method returns the same result. \n");
System.out.println("3 - Split the original array into two arrays, \n" +
" which will store the same type of elements. \n");
System.out.println("4 - Display the array(-s) to the screen.\n");
System.out.println("Any key - Exit the application.\n");
}
}
An example of how the program works:
I fill the array and immediately output it to the console: https://prnt.sc/113qmkr
I get the result:
https://prnt.sc/113qurt
https://prnt.sc/113qvaq
I try again to display all the objects in the array: https://prnt.sc/113qvz4
And... I get completely different results:
https://prnt.sc/113qwhx
https://prnt.sc/113qwps
Moreover, as you may have noticed, the length of the array is preserved, but the objects themselves are already different.
Honestly, I don't know what the problem might be, the teacher at the university also threw up his hands, so I will be glad to any criticism, comments and suggestions. Thank you in advance.
I am trying to print out the Depth First Traversal of my "graph" program.
The DepthFirstTraversal(int v) method is supposed to start from the first index, which is supposed to be A. However, it seems like it is skipping this.
Any suggestions?
I have tried changing the value v from 1 to 0, but this just prints an extra 0 on top of the same code.
import java.util.Arrays;
import java.util.Iterator;
public class Graph {
private boolean[][] edges;
private int[] labels;
private int N; //number of vertices;
//constructor. This constructor will create a matrix of size n by n.
public Graph(int n) {
N=n;
edges = new boolean[n][n];
labels = new int[n];
}
//this method will allow user to add an edge
public void addEdge(int source, int target) {
edges[source][target] = true;
}
//this method will return the label of the vertex
public int getLabel(int vertex) {
return labels[vertex];
}
//this method will allow user to remove an edge
public void removeEdge(int source, int target) {
edges[source][target] = false;
}
//this method will allow user to set a label
public void setLabels(int vertex, int newLabel) {
labels[vertex] = newLabel;
}
//this method will return the size of the labels array
public int size() {
return labels.length;
}
//this method will grab the neighbors of the desired vertex
public int[] neighbors(int vertex) {
int i;
int counter = 0;
int[] result;
for (i = 0; i < labels.length; i++) {
if (edges[vertex][i])
counter++;
}
result = new int[counter];
counter = 0;
for (i = 0; i < labels.length; i++) {
result[counter++] = i;
}
return result;
}
//this method will print out the vertices starting from the first value
I tried fixing my code a little, but I ran into another problem.
I do have to use neighbors method and also I cannot use recursion.
public void DepthFirstTraversal(int v) {
boolean[] visited = new boolean[N];
Stack<Integer> stack = new Stack<>();
stack.add(v);
visited[v]=true;
while(!stack.isEmpty()){
int i = stack.pop();
if (i == 1) {
System.out.print("A" + "-");
} else if (i == 2) {
System.out.print("B" + "-");
} else if (i == 3) {
System.out.print("C" + "-");
} else if (i == 4) {
System.out.print("D" + "-");
} else if (i == 5) {
System.out.print("E" + "-");
} else if (i == 6) {
System.out.print("F" + "-");
} else if (i == 7) {
System.out.print("G" + "-");
} else if (i == 8) {
System.out.print("H" + "-");
} else if (i == 9) {
System.out.print("I" + "-");
}
System.out.print(labels[i] + " \n");
int[] neighborsOfI = neighbors(i);
for(int k=0;k<neighborsOfI.length;k++){
int neighborTest = neighborsOfI[k];
if(!visited[neighborTest]){
stack.add(neighborTest);
visited[neighborTest]=true;
}
}
}
}
}
public class graphDemo {
public static void main(String args[]){
Graph graph = new Graph(10);
graph.addEdge(1,1);
graph.addEdge(2,3);
graph.addEdge(3,5);
graph.addEdge(4,7);
graph.addEdge(5,9);
graph.addEdge(6,2);
graph.addEdge(7,3);
graph.addEdge(8,5);
graph.addEdge(9,8);
graph.setLabels(1,9);
graph.setLabels(2,3);
graph.setLabels(3,5);
graph.setLabels(4,7);
graph.setLabels(5,4);
graph.setLabels(6,8);
graph.setLabels(7,6);
graph.setLabels(8,2);
graph.setLabels(9,1);
System.out.println("Depth First Traversal from first value: \n");
graph.DepthFirstTraversal(1);
}
}
I am expecting the Depth First Traversal to start from A and follow the Depth First Traversal until the last element in the graph, but instead I am outputting this:
Depth First Traversal from first value:
A-1
I-9
Java is 0-indexed, meaning that arrays start at index 0. You were creating an array of size 10, but using the latter 9 entries. I changed your input data to match this, but it wasn't the issue.
public class GraphDemo {
public static void main(String args[]) {
Graph graph = new Graph(9);
graph.addEdge(0, 0);
graph.addEdge(1, 2);
graph.addEdge(2, 4);
graph.addEdge(3, 6);
graph.addEdge(4, 8);
graph.addEdge(5, 1);
graph.addEdge(6, 2);
graph.addEdge(7, 4);
graph.addEdge(8, 7);
graph.setLabels(0,9);
graph.setLabels(1,3);
graph.setLabels(2,5);
graph.setLabels(3,7);
graph.setLabels(4,4);
graph.setLabels(5,8);
graph.setLabels(6,6);
graph.setLabels(7,2);
graph.setLabels(8,1);
System.out.println("Depth First Traversal from first value: \n");
graph.depthFirstTraversal(1);
}
}
I'm not sure what labels are or mean, so I've ignored them completely along with the neighbors which iterates through these labels. Here's the depth first traversal either way:
private void depthFirstTraversal(int v, boolean[] visitedIndexes) {
if (visitedIndexes[v]) {
System.out.println("Arrived at index " + v +
" with letter " + (char) ('A' + v) +
" but we've already been here, so skipping this.");
return;
}
System.out.println("Traversing index " + v +
" which has label " + labels[v] +
" and here's some letter " + (char) ('A' + v)
);
visitedIndexes[v] = true;
for (int i = 0; i < n; i++) {
if (edges[v][i]) {
depthFirstTraversal(i, visitedIndexes);
}
}
}
I am new to Java programming. I developed a Pizza class that takes for parameters and outputs the description and cost. I developed a PizzaOrderArray class that stores the pizza orders in an array. I have a class containing the main method also.
When I tried to print the values of the orders, nothing prints yet debugging shows that the proper methods and loops were entered.
What am I doing incorrect? I have invested many hours and am still very confused. Any suggestions, please? Thank you! I appreciate it.
Pizza.java
import java.text.NumberFormat;
import java.util.Locale;
public class Pizza {
public Pizza(String size, int numCheeseTop, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
setNumCheese(numCheeseTop);
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_pep = 0;
setNumHam(numHamTop);
pizza_cheese = 0;
}
public Pizza(String size) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza() {
pizza_size = "small";
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza(Pizza copyPizza) {
pizza_size = copyPizza.getPizzaSize();
pizza_cheese = copyPizza.getNumCheese();
pizza_pep = copyPizza.getNumPep();
pizza_ham = copyPizza.getNumHam();
}
//Setters
public boolean setPizzaSize(String size) {
if (size.equalsIgnoreCase("small") || (size.equalsIgnoreCase("medium") || (size.equalsIgnoreCase("large")))) {
pizza_size = size.toLowerCase();
return true;
}
return false;
}
public void setNumCheese(int numCheeseTop) {
pizza_cheese = numCheeseTop;
}
public void setNumPep(int numPepTop) {
pizza_pep = numPepTop;
}
public void setNumHam(int numHamTop) {
pizza_ham = numHamTop;
}
//End of setters
//Getters
public String getPizzaSize() {
return pizza_size;
}
public int getNumCheese() {
return pizza_cheese;
}
public int getNumPep() {
return pizza_pep;
}
public int getNumHam() {
return pizza_ham;
}
//End of getters
public double calcCost() {
if (pizza_size.toLowerCase() == "small") {
return 10 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "medium") {
return 12 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "large") {
return 14 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() != "small" && pizza_size.toLowerCase() != "medium"
&& pizza_size.toLowerCase() != "large") {
System.out.println("Invalid pizza size");
return 0;
}
return 0;
}
public String getDescription() {
return pizza_size + " pizza with " + pizza_cheese + " cheese toppings " + pizza_pep + " pepperoni toppings and "
+ pizza_ham + " ham toppings "; //+ " which is " + money.format(pizza2.calcCost());
}
//private String pizza_size;
//private int pizza_cheese, pizza_pep, pizza_ham;
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
} //End of Pizza class
PizzaOrderArray.java
import static java.lang.System.out;
public class PizzaOrderArray {
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
//private String pizza_size;
//private int pizza_cheese; pizza_pep; pizza_ham;
private Pizza[] pizza;
private int index = 0;
public PizzaOrderArray() {
System.out.println("PizzaOrderArray()");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(int i) {
System.out.println("PizzaOrderArray(int i)");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(PizzaOrderArray poa) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa)");
pizza = new Pizza[poa.index];
index = poa.index;
for (int i = 0; i < poa.index; i++) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa) for loop");
pizza[i] = new Pizza(poa.pizza[i]);
}
}
public void setPizza(int index1, Pizza newpizza) {
System.out.println("Inside of setPizza");
pizza[index1] = new Pizza(newpizza);
}
public String getPizzaSize() {
System.out.println("Inside of getPizzaSize");
return pizza_size;
}
public int getNumCheese() {
System.out.println("Inside of getNumCheese");
return pizza_cheese;
}
public int getNumPep() {
System.out.println("Inside of getNumPep");
return pizza_pep;
}
public int getNumHam() {
System.out.println("Inside of getNumHam");
return pizza_ham;
}
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for (int i = 0; i < indexUsed; i++) {
s = (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
return s;
}
public double calcTotal() {
double r = 0.0;
System.out.println("Inside of calcTotal");
for (int i = 0; i < index; i++) {
System.out.println("Inside of calcTotal for loop");
r = r + pizza[i].calcCost();
}
return r;
}
public boolean equals(PizzaOrderArray orderarray) {
boolean r = false;
System.out.println("Inside of equals");
if (orderarray.pizza.length != pizza.length) {
System.out.println("Inside of equals if");
return r;
}
for (int i = 0; i < orderarray.pizza.length; i++) {
if (pizza[i].equals(orderarray.pizza[i])) {
System.out.println("Inside of equals for-if");
r = true;
} else {
System.out.println("Inside of equals for-else");
return false;
}
}
System.out.println("Return of equals");
return r;
}
} //End of PizzaOrderArray class
V4_Project_15_page_418.java
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Arrays;
public class V4_Project_15_page_418 {
public static void main(String args[]) {
//Order1
PizzaOrderArray order1 = new PizzaOrderArray();
Pizza pizzaone = new Pizza("Medium", 0, 0, 0);
Pizza pizzatwo = new Pizza("Small", 1, 0, 0);
order1.setPizza(0, pizzaone);
System.out.println("Order 1: ");
System.out.println(order1.toString());
System.out.println(order1);
System.out.println();
//Order2
Pizza pizzathree = new Pizza(pizzatwo);
PizzaOrderArray order2 = new PizzaOrderArray(2);
order2.setPizza(0, pizzaone);
order2.setPizza(0, pizzatwo);
System.out.println("Order 2: ");
System.out.println(order2.toString());
System.out.println(order2);
System.out.println();
//Order3
PizzaOrderArray order3 = new PizzaOrderArray(1);
order3.setPizza(0, pizzaone);
order3.setPizza(0, pizzatwo);
System.out.println("Order 3: ");
System.out.println(order3.toString());
System.out.println(order3);
System.out.println();
//Order4
PizzaOrderArray order4 = new PizzaOrderArray(order3);
System.out.println("Order 4: ");
System.out.println(order4.toString());
System.out.println(order4);
//TEST THE PROGRAM
System.out.println("TEST: The total for order 4 is: " + order4.calcTotal());
System.out.println();
//Order5
PizzaOrderArray order5 = new PizzaOrderArray(order1);
System.out.println("Order5: ");
System.out.println(order5);
System.out.println();
}//End of main class
}//End of V4_Project_15_page_418 class
Output:
PizzaOrderArray()
Inside of setPizza
Order 1:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 2:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 3:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order 4:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
Inside of calcTotal
Inside of calcTotal for loop
Invalid pizza size
TEST: The total for order 4 is: 0.0
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order5:
Inside of toString
Inside of toString for loop
Take a close look at the condition in this for loop, it isn't going to ever print anything since the condition is never true since i is never less than indexUsed which is 0.
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
return s;
}
Something also need pay attention to:
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
means:
for(int i = 0; i < indexUsed; i++) {
s= (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
So this is System.out.println just misleading you, you are never "inside of" the for loop.
I think it's better to always use the braces '{}' with for/while loop.
The snippet
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString()); is wrong, your for loop is never executed since indexUsed is 0
In your toString method, the for loop condition never becomes true (before the first iteration itself, 0<0 becomes false & loop terminates without executing once) so the loop never executes.
You can try changing the for loop statement to:
for(int i = 0; i < index; i++)
I have written a program which takes the words the user have entered, with a button press, and puts them in an ArrayList. There is also another text field where the user can enter a letter or word, for which the user can search for in the ArrayList with another button press. I'm using a sequential search algorithm to accomplish this, but it does not work as I expect it to; If the searched word is found, the search function should return, and print out in a textArea that the word was found and where in the array it was found. This works, but only for the first search. If the word is not found, the function should print out that the word was not found. This works as I want it to.
The problem is that after I searched for one word, and it displays where in the ArrayList this can be found, nothing happens when I press the button after that, whether the entered letter/word is in the array or not. It's like the string that the text gets stored isn't changing. I don't understand why... Here below is the custom Class of the search function and then my Main class:
public class Search {
static private int i;
static String index;
static boolean found = false;
public static String sequencial (ArrayList<String> list, String user) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
index = "The word " + user + " exist on the place " + i + " in the Arraylist";
found = true;
}
}
if (!found) {
index = "The word " + user + " could not be found";
}
return index;
}
My Main class:
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> s = new ArrayList<String>();
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtaOutput.setText("");
String word = txtfAdd.getText();
list.add(word);
for (int i = 0; i < list.size(); i++) {
txtaOutput.append("" + list.get(i) + "\n");
}
}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String user = txtfSearch.getText();
txtaOutput.setText("");
String index = Search.sequencial(list, user);
txtaOutput.setText("" + index);
}
Any help is appreciated!
The problem is that you declared your found variable as static. When your first word is found, it is set to true, and nothing ever sets it back to false. Instead of making it a static variable, declare it as a local variable inside your sequencial (it's spelled sequential, by the way) function, just before the for-loop.
In fact, all the variables you've declared as static should be made local. Declaring static variables is never a good idea.
As said by other users:
There is the List#indexOf(Object) method. You should use that instead of reinventing the wheel (unless you need to, and in that case you might have a look at the ArrayList implementation). There are also other collections, like HashSet which are more apropiate for looking up, but i guess that is another history.
The scope and the names of the variables (i, index, found) is error-prone. Do other methods or even classes need to have access to those variables? If you need to keep those variables, you might want to choose a visibility (public,protected,private). "index" is a misleading choice of a name for a message.
This would be an slightly simplified/corrected version of your code:
// Ommit those unneeded static variables
public static String sequencial (ArrayList<String> list, String user) {
int indexFound = list.indexOf(user);
if (user >= 0) {
return "The word " + user + " exist on the place " + indexFound + " in the Arraylist";
} else {
return "The word " + user + " could not be found";
}
}
...
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
String user = txtfSearch.getText();
// txtaOutput.setText("");
String seqMessage = sequencial(list, user);
txtaOutput.setText(seqMessage);
}
We use the static properties when you would like to use the constants. You should not use the static properties here. The problem will happen when your found property is changed the first time, it will not be changed again. And from that time, it will always be true. Similar with index property. Here is the code you can fix this:
public class Search {
public static SearchResult sequencial (ArrayList<String> list, String user) {
SearchResult result = null;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
String index = "The word " + user + " exist on the place " + i + " in the Arraylist";
boolean found = true;
result = new SearchResult(index, found);
break;
}
}
if (result == null) {
String index = "The word " + user + " could not be found";
result = new SearchResult(index);
}
return result;
}
//sample inner class
static class SearchResult {
private String index;
private boolean found;
public SearchResult(String index) {
this.index = index;
}
public SearchResult(String index, boolean found) {
this.index = index;
this.found = found;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
}
}
public class SequencialSearcher {
public static int SequencialSearchInt(int[] inputArray, int key)
{
for(int i=0; i < inputArray.length ; i++)
{
if(inputArray[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchString(String[] array, String key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchFloat(double[] array, double key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static void main (String args[])
{
//select the type of the elements of search
//1 if integers
//2 if float
//3 if string
int x = 3;
int[] array1 = {9, 0, 10, 8, 5, 4, 6, 2, 3};
double[] array2 = {9.0, 0.0, 10.0, 8.0, 5.0, 4.0, 6.0, 2.0, 3.0};
String[] array3 = {"aa","hey", "hello"};
if(x == 1){
//enter the integer you want to search for here below
int requiredValue = 5;
int result = SequencialSearchInt(array1, requiredValue);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue+" not found");
}
}
else if(x == 2)
{
//enter the double you want to search for here below
double requiredValue1 = 5.0;
int result = SequencialSearchFloat(array2, requiredValue1);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue1+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue1+" not found");
}
}
else if(x == 3){
//enter the string you want to search for here below
String requiredValue2 = "hey";
int result = SequencialSearchString(array3, requiredValue2);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue2+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue2+" not found");
}
}
else{
System.out.println("Error. Please select 1,2 and 3 only");
}
}
}
I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}