How Does CompareTo Work If There Are More Than 2 Elements In List

Jan 8, 2015

Lets suppose that I pass to the sort method a list of 2 objects of the same class (which implements Comparable interface). I read (in head first java) that one object is compared relative to another with one object calling the CompareTo() while the other object being passed as a parameter to the same method. Now am I safe in assuming that the first object in the list calls the method with the second object being passed as a parameter.And also how does the CompareTo() work if there are more than 2 elements in the list. Which objcet calls the method and which is passed as a parameter?

View Replies


ADVERTISEMENT

Sort String List Alphabetically With CompareTo Method / If Else Statements - Logic Errors

Oct 6, 2014

I'm having trouble with sorting Strings- 3 strings inputted by user, and I would like to output them in alphabetical order. I've used the str.compareToIgnoreCase method, and then I've tried to loop them through a series of if/ else statements. Everything I've been able to find online (including the forums here) has suggested to use the Comparator class, or to put the strings into an array, and sort list- I really would like to stick with just the String class, and its methods .

The program itself works and compiles, but I am getting logic errors that I have been unable to solve. I'm using IntelliJ Idea, and I've ran it through the built in debugger, about 100+ times (not exaggerating, lol) just to see what it's doing in particular scenarios. For instance, I can get c, a, b, to print out as a,b,c correctly, but a,b,c, will print out as b,a,c.

For me this is kind of like a Sudoku puzzle, or a Rubik's cube! Each time I fix one scenario, it breaks another one, so I don't know if there's a(logic) solution to fix all possible scenarios (abc, acb, bac etc... to all print abc) or if possibly I just need more if statements. I've only pasted in the area where I'm having problems (the if statements). I'm a big fan of the "Next Line" syntax.

(Note: please assume the non relevant content- import Scanner class, main method, etc... I didn't want to paste the entire program.)

System.out.println("Enter the first statement: ");
//input.nextLine();
string1 = input.nextLine();
System.out.println("Enter the second statement: ");
string2 = input.nextLine();
System.out.println("Enter the third statement: ");
string3 = input.nextLine();

[Code] ....

View Replies View Related

Adding Elements To A List

Feb 6, 2014

Here is a small part of my program

Java Code:

// for every attribute not mentioned in the rule r
enumAtt = ruleE.enumerateAttributes();
while (enumAtt.hasMoreElements()) {
Attribute attr = (Attribute) enumAtt.nextElement();
if (isMentionedIn(attr, r.m_test)) {continue;}
int M = attr.numValues();

[Code] ....

It repeats only the last rule , why is that !!!!!!

View Replies View Related

Reversing Elements In The List

Feb 14, 2014

i have the following code to reverse the elements of the list but i only print the last element each time

public void reverse(OrderedList<T> lister) {
OrderedList<T> listerCopy = lister;
for(int i=0;i<5;++i) {
T removed=removeFromBack(listerCopy);
System.out.printf("%s ", removed);

[Code] .....

View Replies View Related

Associating Properties With Array List Elements?

Dec 17, 2014

In my project I need to create a pizza ordering system. I have created a array list of pizza toppings and each pizza topping must have a cost property associated with it, then the user can pick the toppings they want and the cost of each topping will be added up and the total cost of the whole pizza will be displayed. But I don't know how to associate a cost with each topping. I have been told that I can access the cost through a get/set method and store it in a private member variable. But I don't know how to do this?

I've tried to do it, but it hasn't worked. This is the code

public void setCost( double cost){ //my get/set method
this.cost = cost;
}
public double getCost(){
double price = 0;
return price;

[Code] .....

But there is an error on each of the ingrediantCost method lines, saying

The primitive type double of cost does not have a field Pepperoni

...and the same for chicken, ham and onion.

View Replies View Related

Reusing Entered List Of Array Elements

Sep 11, 2014

If you see in the code below where I print "Would you like to use previous key" I need to be able to save the previous key answers to be used again.. not sure how to go about doing this..

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] studentName = new String[20];
int[] studentAverage = new int[20];
Scanner input = new Scanner(System.in);

[Code] .....

View Replies View Related

Elements Of Circular Doubly Linked List

Feb 12, 2015

For the program I have to create, I need to be able to work with the elements of a circular doubly linked list to do the following:

Find an element in the list (specified as an argument)
Insert an element after a specified element (specified as an argument)
Delete an element (specified as an argument)
Display the elements in the list

I can insert elements and display the elements, but I can't figure out how to search for an element, insert an element after a specified element, or delete an element.

What I am having trouble with is passing the elements in the list as arguments for searching, deleting, inserting after an element.

public class doublyLinkedList {
private Node pointer;
private Node dLL;
private int count;

[Code] .....

View Replies View Related

JSF :: Create A List Or Array Of Child Elements To Feed To Java Bean

Feb 5, 2014

I have a project I am currently working on using Primefaces and MySQL. I have a page that will display information queried from the database. I have textfields that will display the data from a given record. But I want to ensure that the displayed data cannot be altered. I decided on disabling the textfields unless the create or edit button were clicked. At which point all textfields will be enabled for editing, and cleared if create button was clicked. I want to push the disabling/enabling of the elements back to a managed bean, but I want to have the bean take in two lists or arrays, one containing all elements by ID and one containing a list of exempt elements. Is there a way I can create a List or Array of the ID's that I can send to the bean? I know little in Javascript and previous attempts to implement it have met with little success.

A short example of the code:

<p:tabView>
<p:tab id=pmDBTab title="PM Database Tab">
<p:panelGrid id="projectInfo">
<p:row id="rowOne">
<p:column id="r1c1" colspan="2">
<p:outputLabel id="searchLabel" for="searchField" value="Search: " style="font-weight: bolder"/>

[Code] ....

I want to create a list that would contain all and another that would contain the exemptions such as searchField, searchCriteria, searchButton, projectList and viewButton. The actual exemption list is far smaller than the list of all children. I have found sources that can disable the elements with a java bean, but I have not been able to find one that would allow me to define those that should and should not be disabled, then vice versa for enabling.

View Replies View Related

Declare Array Of 50 Elements Of Type Double - Print Output 10 Elements Per Line

Feb 5, 2015

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class array
{
public static void main(String[] args)

[Code] ...

Is there a way to write this, where, alpha is one array.

Write a program that declares an array "alpha" of 50 elements of type "double". Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable. Output the array so that 10 elements per line are printed.

If I have an array of 50 integers, can I break that to read in lines of 10?

View Replies View Related

Casting For CompareTo

Nov 11, 2014

I am trying to compare some items from a generic arraylist with each other, but I keep getting an error stating that I need to cast the values in line 38. However, when I heed the warning and change it to what it wants, I get a warning stating "type safety: Unchecked cast from K to Comparable<K>". Should I ignore this warning or is there a better way to compare the two items? Also, is there another way for me to use compareTo w/o making my class extending/implementing comparable or is that the only way?Here is what I have:

class WordInfo<K, V extends Comparable <K>> {
private FileReader fr;
private String word;
private ArrayList<K> list;
private BufferedReader br;
private int current = 0;

[code]....

View Replies View Related

How To Sort Names Using Compareto

Feb 24, 2014

i have this problem with my code. it need to put three names in alphabetical order that are entered from the user. then output the alphabetical result. the program compiles but when you put in different names there are not alphabeticals. i think only the first if works good.

import javax.swing.JOptionPane;
public class Sort
{
public static void main(String[] args)
{
String name1;
String name2;
String name3;
 
[code]...

View Replies View Related

Add Elements To 2D Array Without Losing Elements

Jan 12, 2015

I am trying to make a 2d array that keeps track of comparison counts. what I have so far works ok but writes over the previous elements with 0. can't seem to find where I am re-initializing the previous elements.

//this is one of my fill sort arrays

public void fillSelectionArray(int index, long countSum) {
//rand = new Random( );
//for ( int i = 0; i < listsize; i++) {
selectionList[ index -1] = countSum;
// }

[Code] ....

I know I am missing something just not sure what.

View Replies View Related

Inventory Program - CompareTo Not Working

Jul 16, 2014

My instructor gave me this code to use as my Array sort. I can not get this to work. I do not get any compile errors, the code just does not do anything.

Java Code:

package inventoryprogram4;
import java.util.Scanner;
public class Inventoryprogram4
{
static GUI mainGUI = new GUI();
static String outText = "";

[Code] .....

View Replies View Related

Overriding CompareTo From Comparable Interface

Oct 31, 2014

Here is my code:

/*
* Implement the Comparable interface on objects of type Order.
* Compare orderId, then productId. The lesser orderId should come first. If the orderIds match, then the lesser productId should come first.
*/

@Override
public int compareTo(Order ord) {
// TODO Auto-generated method stub
if(orderId > ord.orderId){
return 1;

[Code] ....

Here is the output:

Actual: 0
Expected: -1
Actual: -1
Expected: -1
Actual: 1
Expected: 1
Actual: 1
Expected: 1
Actual: 0
Expected: 0
Actual: 0
Expected: 0

In short, the "Actual" is what my code produces and the "Expected" is what it is supposed to produce. As you can see, only the first one is mismatching... I'll admit, the comment section above the method is confusing and I wasn't exactly sure what it wants me to do, but I thought I figured it out. I just don't see how 5/6 of these tests can work and the 6th one not.

View Replies View Related

Implementing CompareTo Method Of String Class

Apr 26, 2015

I've tried implementing the compareTo method in several ways and no luck.. I keep getting errors and now it just says bad operand type for binary operator with the ">" symbol and also the less than. I'm attempting to give an implementation for the compareTo method so it compares the value of the requestDate instance variable of the two objects. if the calling object of request is greater then I have to return ""1" if it's smaller then returns "-1" and if they are the same then returns value of "0"

package librarysystem_phase2;
import java.io.Serializable;
/**
* This class represents a request a member makes to checkout or download an item from the library.
*/
public class Request implements Serializable, Comparable<Request>

[code]....

View Replies View Related

CompareTo Statement - Null Pointer Exception

Apr 16, 2014

I am getting a NullPointerException at my compareTo statement in this section of my code. Why this is popping up?

public static int findPos(String theArray[], String playerName, int arrayCount)
{
int index;
int pos;
for(index = 0; index < arrayCount; index++) {
while ((index < arrayCount) && (playerName.compareTo(theArray[index]) > 0)) {
index++;
}
}
pos = index;
return pos;
}

Error is also creeping up on the line highlighted in a comment as "THIS LINE", and is linked to the compareTo error above.

while(yesOrNo == 'Y' || yesOrNo == 'y')
{
switch(option)
{
//Add a Player and their Stats to the Array

[Code] ....

View Replies View Related

CompareTo Function To Identify Relationship Between Two Values In Array

Mar 28, 2014

I am having difficulty with a sorting routine. I believe that the concept is valid (although not necessarily the most efficient), but I keep running into a problem. I am trying to use the compareTo function to identify the relationship between two values in an array, but it seems to have an issue with it being a comparison of two float values.

Java Code:

for (int x = 0; x < 430; x++) {
for (int y = 0; y < 430; y++) {
if (dataArray[y].compareTo(dataArray[y + 1]) > 0); {
tempOpen = dataArray[y];

[Code] ....

It gives the compile error as follows:

File: C:UsersBradDownloadsAssignment 3Calculations.java [line: 157]
Error: Cannot invoke compareTo(float[]) on the array type float[]

View Replies View Related

Sort ArrayList By Object Field WITHOUT Using CompareTo Methods?

Mar 9, 2014

I have a project where I must sort a collection of songs by a number of fields: year, rank, title and artist. in the project, we must use certain methods and we cannot add others without getting marked down. Here are the specific requirements:

Sorting

The -sortBy option will cause the output to be sorted by a particular field. If this option is specified, the output should be ordered according to the field named. If there are ties, the tied songs should appear in same order in which they were in the input file. If no -sortBy option is specified, the output should maintain the order of the input file.

public void sortYear()

Order the songs in this collection by year (ascending).public void sortRank()
Order the songs in this collection by rank (ascending).public void sortArtist()
Order the songs in this collection lexicographically by artist (ascending, case-insensitive).public void sortTitle()
Order the songs in this collection lexicographically by title (ascending, case-insensitive).

Here is the relevant code:

SongCollection Class
Java Code: import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;

[code]....

View Replies View Related

Sort Linked List Through The Nodes Of List - Data Of Calling Object

Feb 14, 2014

I have some class called sorted to sort the linked list through the nodes of the list. and other class to test this ability, i made object of the sort class called "list1" and insert the values to the linked list.

If i make other object called "list2" and want to merge those two lists by using method merge in sort class. And wrote code of

list1.merge(list2);

How can the merge method in sort class know the values of list1 that called it as this object is created in other class.

View Replies View Related

How To Append New Entry In A List Of 100,000 Names Without Iterating List Each Time

Apr 22, 2015

I have a list of 100,000 + names and I need to append to that list another 100,000 names. Each name must be unique. Currently I iterate through the entire list to be sure the name does not exist. As you can imagine this is very slow. I am new to Java and I am maintaining a 15+ year old product. Is there a better way to check for an existing name?

View Replies View Related

Unable To Filter A List And Then Assign Results To New List

Dec 30, 2014

I receive a java.lang.NumberFormatException: For input string: ""DepDelayMinutes"" error when trying to filter a list and then assign the results to a new list.

I have edited the code so it is an int that throws the exception so it isn't the presence of a string that is causing the error - java.lang.NumberFormatException: For input string: ""0914"" .

I believe the issue is because of the two sets of double quotes but I do not understand how they came about. The original dataset does not have any quotes whatsoever.

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class FilterObjects extends Thread{

[Code]...

View Replies View Related

Iterating Over List And Inserting Each Element From List Into BST?

Jul 5, 2014

Suppose i have given a List<Intervals> list; I am iterating over list and inserting each element from list into BST, if time require to insert into BST is logn then what is the total time require to insert all the elements into tree ?

logn or nlogn ?

View Replies View Related

Linked List Implementation Of List Interface?

Oct 5, 2013

So we have an assignment regarding a linked list implementation of a given list interface.

In my list interface, the method contains(T anEntry) is defined.

In the LList implementation, contains is already implemented as part of getting the core methods in.

Now I am being tasked with the following:

Provide a second implementation of the method contains2(T anEntry) that calls a private recursive method

Private boolean contains (T anEntry, Node startNode) that returns whether the list that starts at startNode contains the entry anEntry.

I've written the private recursive method already. That's not an issue (at least not right now).

But what I don't understand is how startNode is supposed to be populated when this private contains method is called from the public contains2 method? contains2 only takes one parameter: anEntry. the private method takes two parameters: anEntry and startNode. How am i supposed to provide startNode when I am calling contains2?

View Replies View Related

Add To List With ID Makes List Upside Down

Feb 14, 2015

I saved the content of an ArrayList<SomeClass> to a file

I write each serialised object to the file by adding to each an id that is created with list.indexOf(object) (and saved before each object)

So I can repopulated the list with SomeClass objects in the same order as they were and once I reload the file, I do list.add(id,object)...

Well my list is populated upside down, I mean the first object is the last and the other way around, If i remove the id when I do the add(object)...

View Replies View Related

How To Add Elements To A Map

Mar 13, 2015

I have a requirement to add elements to a map. But for, First iteration it inserts fine and for next iteration elements are overrided.

I am just wondering if there were append() in map or in any collections?

View Replies View Related

Why Not Getting All The Elements In TreeSet

Aug 1, 2014

public void createPersons() {
Random rand = new Random();
for(int index = 0; index < persons.length; index++) {
Person person = new Person(rand.nextInt(maxAge), persons[index]);
setOfPersons.add(person);

[Code] ....

setOfPersons is a TreeSet, persons[] is an array of strings that contains 10 names. Why printPersons() prints only the half names of setOfPersons?

Note. I do get the size of the TreeSet as 10...

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved