I'm new to object oriented programming, my previous experiences have been in C. I was given an assignment to implement an operation to transform a list of data by creating a partitioning algoritm.
import java.util.*;
public class Partition {
public static void partitionWithSetGet ( List<String> theCollectionOfData ) {
int i, j;
while(i <= j){
int Result = theCollectionOfData.get(i).compareTo(pivot);
int Result = theCollectionOfData.get(j).compareTo(pivot);
[code]....
I want to grasp the this concept in greater detail, then I can use the Java API to figure out the syntax!
Referring Code 1, the book says line 16 of the code removes the element "Three" but line 17 does not remove the element "Four" because of Statement 1. The question is does remove(Object o) method invoke the == or the equals method because statement 1 and 2 seem to be in conflict
Statement 1:
Two objects are equal if their object references point to the same object. (which is nothing but definition of ==)
Statement 2:
The author refers to Statement 1 and says "As mentioned earlier, the method remove compares the objects for equality before removing it from ArrayList by calling method equals."
Java Code:
import java.util.ArrayList; public class DeleteElementsFromArrayList { public static void main(String args[]) { ArrayList<StringBuilder> myArrList = new ArrayList<>(); StringBuilder sb1 = new StringBuilder("One");
I have a 2D arraylist, named as adjLists, which contains arraylists, containing values like these. Each two values are a "pair" and each third is a "flag" for the pair.
I use code above to search for specified value pairs in these lists. vertexnum is the number of "sub arraylists" in adjLists.
for (int l = 0; l < vertexnum; l++) { if (adjLists.get(l).get(0) == p.x && adjLists.get(l).get(1) == p.y) { for (int h = 0; h < adjLists.get(l).size(); h += 3) { for (int g = 0; g < vertexnum; g++) { if ((vertexSprite[g].getX() + vertexSprite[g].getWidth() / 2) == adjLists.get(l).get(h)
[Code] ....
This code is to search exact values and replace their flag in every occurences. It can not find all the occurences of the values/pair in the lists, it replaces flag value only a few time. Value of score should be incremented with plus 1 after each found occurence, but this code increments it more than the number of matches.
I have an ArrayList of tens of thousands of elements, and want to remove the items at a given set of sorted indices like {1,5,29,318,499,583}. It seems like this operation could be performed in linear time and space by first finding a cumulative sum of the shifts needed to move everything to their right positions and then shifting every item. On the other hand, removing and shifting one by one would seem to require many more shifts. Is there a way to do this in Java's ArrayList?
The number of Contact that I input is just one when I run the program so the Number of contacts: 1 is correct, but it gives me workbook.Contact@46e5590e instead of printing out all the contacts stored inside the Contact class. Yes I do loop through the ArrayList and I also have a method inside the Contact class, the printNameAndPhone(), which prints out the name as well as the phone number but how do I incorporate the printNameAndPhone() method (located in the Contact class) inside the print() method (located inside the AddressBook class)???
Basically I'm asking how to access all the elements in the ArrayList<Contact> addressBook = new ArrayList<>();??My main class AddressBook
package addressbook; import java.util.Scanner; import java.util.ArrayList; public class AddressBook {
how to read and understand the API's. I've got an array list and I was wondering if there was a method that can randomly re arrange the elements in terms of their index positions.
Scanner in = new Scanner(System.in); ArrayList<rand> selectedRand = new ArrayList<Rand>(); selectedRand.add(new Rand(in.nextLine()));
I have created the most minimal code for creating an array list. I was wondering what the basic syntax of accessing objects methods that are within an Array List. So if I was to trying and get a method such as [.returnValue,] how would this look within a Rand object that is declared in a Array List Since you cannot simply declare a new Rand object and say:
newRandObject.returnValue();
And you must go through the actual slotted portion of the array list. I have searched the web and my text book for an example however none are provided.
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).
I've tried a couple ways to do it, and they don't work. I'm aiming for functionality like I got with the regular for loop, but from an enhanced for loop. Is this simply beyond the scope of an enhanced for loop, or am I just not getting the right syntax?
TestObject to1 = new TestObject("first", 11); TestObject to2 = new TestObject("second", 12); TestObject to3 = new TestObject("third", 13); TestObject to4 = new TestObject("fourth", 14); TestObject to5 = new TestObject(); List<TestObject> testList; testList = new ArrayList<TestObject>();
[code]....
The TestObject class is simply an int and a String, with getters getInt and getString. It all works fine with the regular for loop.
edit: I should probably mention that I know what I have in the enhanced for loop now will only display the class name and the hash. I've tried adding the .getString and .getInt, and tried a few other ways to make it work. I just reverted to this because it compiles and runs
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?
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; // }
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?
I have stumbled onto a problem with ArrayLists (not sure if nested ArrayList objects would be a more accurate description) ....
As simply put as I can describe it, I have an Inventory class which creates an ArrayList of a Product superclass, which has two subclasses, PerishableProduct and ItemisedProduct.
By default, the program is meant to have a starting inventory, which is why I have added them in the constructor
public class Inventory { private List<Product> products; public Inventory() { addProduct(new Product("Frying pan", 15, 20)); addProduct(new PerishableProduct("Apple", 5.8, 30, 7)); addProduct(new ItemisedProduct("Cereal", 5.8, 0)); // this is where I am having problems. Wanting to add // objects to the ItemisedProduct's ArrayList for cereal. }
Within the ItemisedProduct subclass is yet another ArrayList which is meant to hold serial numbers.
public class ItemisedProduct extends Product { private ArrayList<String> serialNumbers = new ArrayList(); public ItemisedProduct(String name, double price, int qty) { super(name, price, qty)
[Code] .....
My problem is that I do not know how to populate the serialNumbers ArrayList from the Inventory class' constructor. Because technically, quantity is defined by how many serial numbers are created.
The library array has two books and I want to copy one of them to the reserved books when you type in the ISBN
public void borrowBook(String ISBN) { int i = 0; if(numberOfBooks < MAX_BOOKS-1) { if(libraryBooks[i].getBookISBN().equals(ISBN)) { for(i=0;i<MAX_BOOKS-1;i++) reservedBooks[i] = libraryBooks[i]; } else System.out.println("There is no such book"); } else System.out.println("You have reached the maximum number of allowed books"); }
It shows me error: incompatible types - LibrarySystem cannot be converted into ReservedBook. How can I fix it?
I would like to create a java gui (with CRUD elements) that connect to MySQL server DB and display a table records (also insert, edit, delete data to table), and I want to know how create such a gui.
So I am trying to create a code that searches if a word is square free. The user inputs a word (into an array) and then the code is suppose to see if it is square free. A word being square free means that the word doesn't contain any consecutive sub words. For example, "abcabc" is not a square free word because abc is repeated, but "abcdabc" is a square free word because there is a "d" separating the "abc".
So far I have this :
import java.util.Scanner; public class A3Q2 { public static void main(String[] args) { // part (a) of the main Scanner keyboard = new Scanner(System.in);
[Code] ....
I've been trying to experiment with different ways such as checking to see if there any duplicate elements such as,
public static char isSquareFree(char[] word){ for(char i = 1; i < word.length; i++) { if(word[i] == word[i - 'a']) { System.out.println("Duplicate: " + word[i]); } } return word; } }
// 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 !!!!!!
I'm currently in the process of creating a shopping cart simulation. The main GUI consists of two lists, one is a list of the inventory. (products stored within a .dat file which is automatically loaded upon launch) The other is blank and is to model my shopping basket. The idea is to be able to scan items from my inventory into the checkout basket. As this is happening i want a text field i created to dynamically update with the cost of all the items in the basket.
Below is the method for my scan button, which is supposed to perform the above :
public void actionPerformed(ActionEvent evt) { //Get the newly added list values. JList list = productList.getSelectedValuesList(); double totalAddedValue = 0.0; double oldCartValue = 0.0;
ok so for class I'm supposed to Write a class DeleteElements that prints out an array and asks the user which number should be deleted and then deletes that number, if it exists from the array.
The first part tells me to
Step 1 o Start by simply searching the element.
o Pseudocode: -Create an array and populate it with random positive integers. -Print the array to show the user which elements the array contains. -Use a WHILE loop to search the element—a WHILE loop is better than a FOR loop because you can stop when the element is found by using a Boolean value in the loop condition—and also keep track of the location where the element might be found. -If the element is not found, output the error message, “Number not found.” -Otherwise output the message, “Number found at index #.” where # is the index where the element is. -Print out the array.
Example of output: 34 65 12 76 45 39 86 71 67 Number to delete: 76 Number found at index 3
This is what I've got so far but I can't seem to get the "number not found part to print out only once".
public class DeleteElement { public static final int ARR_LENGTH = 10; public static void main(String[] args) { Scanner input = new Scanner(System.in); Random ran = new Random();
[Code] ....
Current output result if value does not exist:
61 89 52 16 20 71 37 91 4 36 Number to delete: 23 Number not found. Number not found. Number not found. Number not found. Number not found. Number not found. Number not found. Number not found. Number not found. Number not found. Current output result if value exists:
97 48 51 22 89 5 42 97 43 96 Number to delete: 89 Number found at index 4
Maybe I'm not understanding the part about the boolean value.
I have tried to print array elements using standard print statement. I am getting errors. How to print them. Here is my code:
class arrayEx1{ public static void main(String args[]) { int a[]=new int[3]; //Declaring Single Diomentional Array a[0]=10; a[1]=20; a[2]=30; int total=a[0]+a[1]+a[2]; System.out.println("Values stored in a[0],a[1],a[2]elements are :" + a[0] a[1] a[2]); System.out.println("Total values of a[0],a[1],a[2]elements is :"+ total); } }
if i give comma (,) in between above print stament (print statement 1) stil i am getting errors.