Binary Search output issue? - java

This is a first for using a binary search for me, so I've run into a small issue (hopefully!) first the program, it allows the user to type in a random number, and if that number matches any book it outputs the title.
class b {
String book1, book2;
b () {
book1 = "Wicked Awesome Title";
book2 = "How to Read a Book";
public static Book getBook(Book [] A, int left, int right, String bookTitle) {
int middle;
Book found = null;
/**Your average Joe binary search...*/
while (found == null && left <= right) {
//If middle item == 0, returns true
middle = (left + right)/2;
int compare = A[middle].sameTitle(bookTitle);
if (compare == 0) {
found = A[middle];
} else {
if (compare >0) {
right = middle -1;
} else {
left = middle + 1;
}
}
}
return found;
}
Now this is the problem, after pressing the "find" book button,
private void findActionPerformed(java.awt.event.ActionEvent evt) {
String book1 = "Wicked Awesome Title";
String book2 = "How to Read a Book";;
Book b = getBook(book1, book2); //this entire line is underlined,
if (b != null){
itsATextField.setText("You've found the book " + b);
}
so what am I missing to make this work? Any ideas?

Your getBook function is declared as:
public static Book getBook(Book [] A, int left, int right, String bookTitle) {
When you try to call it only with two String arguments:
Book b = getBook(book1, book2);
If you want to call a function, you must call it with the expected arguments.
Also, not sure if related or not but you'r missing } at the end of the constructor.
BTW, adding the error you get will help us help you.

Related

Why is my code skipping over certain elements in a txt file?

I'm currently working on an assignment that requires me to build a small database for an imaginary toy company. They sell four different types of toys, with all of their toy's data in a single text file. Different toys have varying attributes to them.
My job is to read every line of the text file, find out what toy it is based on it's serial number, create a new instance of that toy, and load it into an array list of Toys.
Here are some examples of a line in the .txt file for every type of toy.
Animal
2835360879;Cow;Game Assassin;19.52;3;7;Plastic;M
Puzzle
4353818087;Eight queens puzzle;Gamescape;15.69;5;6;C
Figure
1147205649;Ninja Turtles;Gamezoid;46.15;10;6;A
Board Game
7235647474;13 Dead End Drive;Game Assassin;55.18;10;9;1-8;Emeli Davis
The following method is in charge of parsing through the text file, to create new instances of Toy, and to add them into the Array List
public void loadData() {
try {
File dataFile = new File("res/toys.txt");
if (dataFile.createNewFile()) {
System.out.println("Data file created!");
}
else {
Scanner readData = new Scanner(dataFile);
readData.useDelimiter(";"); // sets semicolons as the delimiter
while(readData.hasNext()) {
sn = readData.nextDouble(); // reads the next double (serial number) on each line
category = categoryHandler(sn); // setting and returning value for category based on the serial number
nm = readData.next(); // initializes the name of the toy
brd = readData.next();
prc = readData.nextDouble();
availableCnt = readData.nextInt();
ageApp = readData.nextInt();
// creates a new object, dependant on the category
switch(category) {
case "Figures":
char classification = readData.next().charAt(0);
Figure figures = new Figure(sn, nm, brd, prc, availableCnt, ageApp, classification);
data.add(figures);
break;
case "Animals":
String material = readData.next();
char size = readData.next().charAt(0);
Animal animals = new Animal(sn, nm, brd, prc, availableCnt, ageApp, material, size);
data.add(animals);
break;
case "Puzzles":
char puzzleType = readData.next().charAt(0);
Puzzle puzzles = new Puzzle(sn, nm, brd, prc, availableCnt, ageApp, puzzleType);
data.add(puzzles);
break;
case "Board Games":
String playerCount = readData.next(); // holds the player count as a string
int minPlayers = Integer.parseInt(playerCount.substring(0, 1)); // holds the first integer
int maxPlayers = Integer.parseInt(playerCount.substring(playerCount.length() - 1, playerCount.length())); // holds the second integer
String designers = "";
BoardGame boardGames = new BoardGame(sn, nm, brd, prc, availableCnt, ageApp, minPlayers, maxPlayers, designers);
data.add(boardGames);
break;
default:
System.out.println("Invalid toy type selected!");
}
if (readData.hasNext()) {
readData.nextLine(); // skips to the next line if there's a line to skip to
}
}
readData.close();
}
}
catch (IOException e) {
System.out.println("An error occured.");
e.printStackTrace();
}
}
The following method is in charge of categorizing the toy type.
public String categoryHandler(double serialNumber) {
String serialNumCheck = Double.toString(serialNumber); // converting serial number to string to allow the first digit to be checked
double firstDigit;
// setting up the first digit, checking to see if it's zero.
if (serialNumCheck.length() == 12) {
firstDigit = 0;
}
else {
firstDigit = Double.parseDouble(Double.toString(serialNumber).substring(0, 1));
}
// conditionals
if (firstDigit == 0 || firstDigit == 1) {
category = "Figures";
}
else if (firstDigit == 2 || firstDigit == 3) {
category = "Animals";
}
else if (firstDigit == 4 || firstDigit == 5 || firstDigit == 6) {
category = "Puzzles";
}
else if (firstDigit == 7 || firstDigit == 8 || firstDigit == 9) {
category = "Board Games";
}
// this condition should not be possible to achieve, unless the first digit is negative. Still have it just in case.
else {
System.out.println("Invalid serial number created!");
category = "";
}
return category;
}
After running the loadData() method, my array list only contains 128 toys, instead of the expected 225. Almost all of them are categorized properly, but a few toys are not, at seemingly at random indices.
I suspect it has something to with readData.nextLine() at the end of the loadData() method. The problem is that when I remove the line, the program throws a NullPointerException as there nothing left to scan on the current line, so no Toy can be created.
At this point I'm fairly lost as to what is causing this bug.
Some guidance would be appreciated.

nearest neighbor algorithm copy element (city) to output array java

So I have a program written so far that reads in a csv file of cities and distances in the following format:
Alaska Mileage Chart,Anchorage,Anderson,Cantwell,
Anchorage,0,284,210,
Anderson,284,0,74,
Cantwell,210,74,0,
So the algorithm works and outputs the cities in the order they should be visited following the shortest path using the nearest neighbor algorithm always starting with Anchorage as the city of origin or starting city.
Using this data, the example output for the algorithm is: 1,3,2. I have ran this with a 27 element chart and had good results as well. I am using this small one for writing and debugging purposes.
Ideally the output I am looking for is the Name of the City and a cumulative milage.
Right now I am having working on trying to get the cities into an array that I can print out. Help with both parts would be appreciated or help keeping in mind that is the end goal is appreciated as well.
My thought was that ultimately I may want to create an array of {string, int}
so my output would look something like this..
Anchorage 0
Cantwell 210
Anderson 284
I am able to set the first element of the array to 1, but can not get the 2nd and 3rd element of the new output array to correct
This is the code I am having a problem with:
public class TSPNearestNeighbor {
private int numberOfNodes;
private Stack<Integer> stack;
public TSPNearestNeighbor()
{
stack = new Stack<>();
}
public void tsp(int adjacencyMatrix[][])
{
numberOfNodes = adjacencyMatrix[1].length;
// System.out.print(numberOfNodes);
// System.out.print(Arrays.deepToString(adjacencyMatrix));
int[] visited = new int[numberOfNodes];
// System.out.print(Arrays.toString(visited));
visited[1] = 1;
// System.out.print(Arrays.toString(visited));
stack.push(1);
int element, dst = 0, i;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\n");
//System.arraycopy(arr_cities, 0, arr_final, 0, 1); // Copies Anchorage to Pos 1 always
//System.out.print(Arrays.deepToString(arr_final)+ "\n");
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes-1)
{
if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag)
{
visited[dst] = 1;
stack.push(dst);
System.out.print(dst + "\n");
minFlag = false;
continue;
}
stack.pop();
}
}
Given the existing structure you are using, you can output the cities in the path using:
public void printCities(Stack<Integer> path, int[][] distances, List<String> names) {
int cumulativeDistance = 0;
int previous = -1;
for (int city: path) {
if (previous != -1)
cumulativeDistance += distances[previous][city];
System.out.println(names.get(city) + " " + cumulativeDistance);
previous = city;
}
}
I'd like to answer your question slightly indirectly. You are making life hard for yourself by using arrays of objects. They make the code difficult to read and are hard to access. Things would become easier if you create a City class with appropriate methods to help you with the output.
For example:
class City {
private final String name;
private final Map<City,Integer> connections = new HashMap<>();
public static addConnection(City from, City to, int distance) {
from.connections.put(to, distance);
to.connections.put(from, distance);
}
public int getDistanceTo(City other) {
if (connections.containsKey(other))
return connections.get(other);
else
throw new IllegalArgumentException("Non connection error");
}
}
I've left out constructor, getters, setters for clarity.
Now outputting your path becomes quite a bit simpler:
public void outputPath(List<City> cities) {
int cumulativeDistance = 0;
City previous = null;
for (City current: cities) {
if (previous != null)
cumulativeDistance += previous.getDistanceTo(current);
System.out.println(current.getName + " " + cumulativeDistance);
previous = current;
}
}

Java: Parameter list without comma

I came across a method with a parameter list where the parameter were not separated by comma and no declaration of the variable type:
public int compareWith(Choice anotherChoice){
Later these parameters were called without any further declaration inside the body in an if-else statement in combination with another method:
if ((this.type == 0)&&(anotherChoice.getType() == 1)){
return -1;
This is a brief summary of the entire class:
public class Choice
{
private int type;
public Choice(int type)
{
//initialize the "type" instance varialble
this.type = type;
}
public int getType()
{
return type;
}
public int compareWith(Choice anotherChoice)
{
Choice choice1 = new Choice(0);
Choice choice2 = new Choice(1);
if ((this.type == 0)&&(anotherChoice.getType() == 1)){
return -1;
The program goes on. I really don't get the link between anotherChoice, getType() and choice2. It is a task in an online course and the program works as intended, but I don't know why.
To clear up your confusion, in this method declaration:
public int compareWith(Choice anotherChoice){
anotherChoice is the parameter of type Choice.
I'm guessing you're new to programming, so I'll give a quick explanation of what's going on. If I've missed the point of your question entirely, I'm sorry.
This line:
public int compareWith(Choice anotherChoice){
is part of the Choice object. It takes another Choice object and compares it with itself. ...or at least, that's what I would expect. The code you provided:
public int compareWith(Choice anotherChoice)
{
Choice choice1 = new Choice(0);
Choice choice2 = new Choice(1);
if ((this.type == 0)&&(anotherChoice.getType() == 1)){
return -1;
is incomplete and I have no idea what choice1 and choice2 are supposed to be doing. The code I would expect to see would look more like
public int compareWith(Choice anotherChoice)
{
if (this.type == anotherChoice.getType())
return 0;
return -1;
}
or something like that.
Does that help?
This was my solution for the course. Probably not the best solution but it worked and i receved my grade. I'm at this moment stuck with LAB 04 TASK 3.
int player=this.getType();//get value of choice1
int computer=anotherChoice.getType();// this get the value choise2 out of anotherChoise
int som;// this INT i made to make a sum
int result;
result = 0;//i already gave a value on the INT result
som = player - computer;//this is the sum of de values choice1 and choise2
if(player == computer) //all ties
result = 0;
else if(som == -1) //player ROCK and comp. PAPER or PAPER and SCISSOR
result = -1;
else if(som == 2) //player SCISSOR and comp. ROCK
result = -1;
else if(som == 1)//player SCISSOR and comp PAPER or PAPER and ROCK
result = 1;
else if(som == -2)//player ROCK and comp. SCISSOR
result = 1;
return result; // this line should be modified/removed upon finishing

Binary Search Tree: Display contents of the tree in a tree like fashion (recursive)

I been at it for a while I can't figure it out. I am suppose to do a reverse order traversal (right-root-left) and pass the level of the root to the function ShowTree.
What exactly is the level of the root? Is it the height? If yes, this is the code for it:
public int getHeight()
{
return getHeight(_root);
}
private int getHeight (BSTnode top)
{
if (top == null)
return 0;
else
{
int lftHeight = getHeight(top._left);
int rhtHeight = getHeight(top._right);
if (lftHeight > rhtHeight)
return 1 + lftHeight;
else
return 1 + rhtHeight;
}
}
So I assign the value of getHeight to level and pass it to ShowTree. I am suppose to use the level of each node to compute how many spaces to insert in front of the data of each node.
public String ShowTree (int level)
{
return ShowTree(_root,level);
}
private String ShowTree(BSTnode myroot, int level)
{
String result = "";
if (myroot == null)
return "";
else
{
result += ShowTree (myroot._right, level + 1);
result += myroot._data.toStringKey();
result += ShowTree (myroot._left, level + 1);
return result;
}
}
However this diplays the tree like this:
c
b
a
When it should print like this:
c
b
a
In your ShowTree(BSTnode, int) method...
String result = ""; // no extra whitespace
Dont you mean...
String result = " "; //extra whitespace

Cannot find symbol error

thank you in advance for helping out with this relatively simple (I hope) problem that I seem to be encountering. whenever I try to compile my programming assignment, I am met with a "cannot find symbol error." I point out where the error occurs in the code itself. Thanks again!
public class SSN
{
private int one;
private int two;
private int three;
public SSN(int first, int second, int third) throws Exception
{
if(first > 99 || first < 1 || second > 999 || second < 1 || third > 9999 || third < 1)
{
}
else
{
one = first;
two = second;
three = third;
}
}
//method that turns ###-##-#### string into 3 int SSN object
public static SSN valueOf(String ssn)
{
String firstpart;
firstpart = ssn.substring(0, 2);
String secondpart;
secondpart = ssn.substring(4, 5);
String thirdpart;
thirdpart = ssn.substring(7, 10);
int One = Integer.parseInt(firstpart);
int Two = Integer.parseInt(secondpart);
int Three = Integer.parseInt(thirdpart);
System.out.println(firstpart);
//This is where the cannot find symbol error occurs (return SSN(One, Two, Three), //and I am clueless as to why.
//Any insight as to why this error is occurring would be much appreciated!
return SSN(One, Two, Three);
}
public String toString()
{
return one + "-" + two + "-" + three;
}
}
return new SSN(One, Two, Three);
^^^
You're trying to create a new SSN(...) by calling the constructor.
The compiler si looking for a method named "SSN" but there is not such method ( the compiler can't find that symbol ) You were trying to create a new object not invoking a method thus you need to inlcude the new keyword as Erik and SLaks said.
return new SSN( One, Two, Three );

Categories

Resources