Using Iterators To Compare ArrayLists
Sep 15, 2014
The question states:
>Suppose that aList and bList are instances of java.util.ArrayList. Use two iterators to find and display all the objects that are common to both lists. Do not alter the contents of either list. Write the segment of code assuming that the objects are of type String.
If my understanding is correct, I need to create two Iterators (one for aList and one for bList) to compare both ArrayLists and I should output any value that appears in both lists.
This is my attempt at it:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> aList = new ArrayList<String>();
ArrayList<String> bList = new ArrayList<String>();
aList.add("One");
aList.add("Two");
[Code] ....
The output:
`One`
`Two`
It stops there. It's clear that my loop is wrong, but I don't really know how to go about fixing it.
View Replies
ADVERTISEMENT
Feb 20, 2014
I'm confused on how to provide a trace table with this problem.
int i = 0; int j = 1; int n = 2;
while (i < 10) {i++; n = n + i + j; j++; }
My professor wants us to use iterations as a way to solve it and this was the example given:
int i = 0; int j = 1; int n = 2;
while (i < j) { i ++; j --; n++; }
public static String r43a() {
// START CODE
String answer = "iteration1: i=" + 0 + ", j=" + 1 + ", n=" + 2 ;
answer += "
";
answer += "iteration2: i=" + 1 + ", j=" + 0 + ", n=" + 3 ;
return answer;
// STOP CODE
}
View Replies
View Related
Jun 27, 2014
I have to make ask for 2 houses or more (INSTANSED CLASS, with 2 ints ) with the same size(int ), but i they cant use the same door number(int). how do i check in my ArrayList that they have different numbers while not caring about different size? .
The ArrayList is in a class called system. I dont know if i should try to Override the equal or try something else.
View Replies
View Related
Sep 9, 2014
I have two arraylists. One is personalContactList. The other is businessContactList.
1. I want to take user input that references an object attribute (int),
2. Use it to determine which object is referenced,
3. Find the "type" attribute of that object,
4. Determine which arraylist the object belongs to, based on that type,
5. Use the if else/statement to print out some attributes that depends on which arraylist the object is in.
I believe the code successfully does 1-3, and probably 4. But there is a hangup on 5. I get an indexoutofbounds execption. Which I'm not sure I understand very well.
Here is the code--it's part of a switch statement:
case "c": {
//some code here prints out a list
boolean b = false;
int g;
while (b == false) {
Scanner detailScanner = new Scanner(System.in);
System.out.print("Enter a number to see details: ");
[Code] ....
View Replies
View Related
Feb 25, 2014
I'm new to java and up until now whenever I have created an object it has been via the BlueJ interface. I would make an object manually and then manipulate it with my methods.
I have made a basic program which adds objects into arraylists via the BlueJ interface. However I now need to prompt a user to enter a string which should create the specific object and add to its ArrayList.
Is there a way to create objects without manual specifying the parameters? I can provide some of my code if it is needed I am trying to make a crude version of Plant vs Zombies for an assignment.
I am aware of the scanner class but I only know how to prompt a user but I feel like if I can figure a way to create the objects I can dynamically I can associate the string inputs to the proper arraylists.
View Replies
View Related
Apr 6, 2015
I have two ArrayLists and I want to compare them for common elements, and based on the result I want to update the first Arraylist to only have these elements. sort of like the opposite of RemoveAll() which removes elements in common and keep the ones that are unique. so far I thought of using for loop and .contains() in case it was fault,element not present, remove from list. but I was wondering
in what other ways, perhaps APIs i can use to do that?
View Replies
View Related
Jan 27, 2014
I have this piece of code, which adds marks into 2 different arrayLists, one for homework marks, and one for examination marks..
ArrayList<Double> homeworkMark = new ArrayList<Double>();
ArrayList<Double> examinationMark = new ArrayList<Double>();
boolean markCheck = true;
do{
//
the purpose of this try catch is to make sure that the entered mark is a valid number. If the program encounters an exception markCheck will become true and the loop will begin again asking the user to enter the marks. If the marks are all encountered correctly markCheck will be false and the loop will end.
try{
for (int i = 1; i <= amountAssignment; i++ ) {
sc.reset();
System.out.print("Homework Mark for Assignment " +(i) + ": ");
homeworkMark.add(sc.nextDouble());
System.out.print("Examination Mark for Assignment " + (i) + ": ");
examinationMark.add(sc.nextDouble());
markCheck = false;
[code]....
View Replies
View Related
Jul 8, 2014
So I am learning HashMaps/Arraylists and I can't really understand the diamond operator or what it's for. Take the following code for example: Why could we not just do this without the diamond?
Java Code:
import java.util.HashMap;
class Untitled {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("California","Sacramento");
map.put("Oregon","Salem");
map.put("Washington","Olympia");
System.out.println(map);
}
} mh_sh_highlight_all('java');
View Replies
View Related
Apr 15, 2015
So I have a program where you can log in and add/remove friends to and from the friends arraylist. Also I can like a certain thing and that thing will be stored into the likes arraylist. I'm asked to make undo and redo options for whichever action I do.I want to add apple as a friend. After that when I select the undo option, I can undo that action so apple wouldn't be my friend. How I can approach this with a Command Pattern when the input is whatever name or word I inputted to store into the friends arraylist?
I did some research and found that using a command pattern could be my best bet since this has to be done under the Facebook Class I already have. I decided to add parts of what I have ...
In the driver program
Facebook facebook1 = new Facebook();
if (userInput == 6) {
System.out.println("Login");
String operand1 = getOperand("What is the Username? ");
String operand2 = getOperand("What is the Password? ");
System.out.println("Enter a friend to be added. ");
String operand3 = getOperand("What is the Username? ");
facebook1.friend(operand3);
[code]....
View Replies
View Related
Jun 13, 2014
I have been doing a program that allows the user to input students names and numerical grade values. I have already completed 3/4 of the program but am stuck on the bubblesort method as this is what it requires:
The program must have an indefinite loop, which prompts the user to select a sorting criterion or to end the program, and must also use bubble sort. Note: The user may either select name or grade as the sorting criteria. The program must use bubble sort to sort that data according to the specific criteria and then use another loop to display the data. This process must continue until the user ends the program.
My problem is, while i can easily do the bubblesort, where to look on how to link elements of the two arraylists I'm using (one for grades, one for names) so that when the user decides what sort they want, the individual's name and grade stays together.
View Replies
View Related
Apr 19, 2015
[URL] I made a program that takes 2 stock values by URL tickers, and now I need it to draw a graph with the values for the 2 stocks, so they can be compared visually. So far my idea was to create 2 arraylists that consist of the values for each stock, so that I can draw the graph so that x always move with 1 step, and y0 is the first coordinate, and y1 is the second, and after that y1 is the first, y2 second etc.
View Replies
View Related
Feb 22, 2014
I have come across an issue with arraylists. I am writing a text based RPG game as something to start with ...
Initially I had a single zone which was all stored in an arraylist and everything was working in regards to the player moving around. The problem I now have is how to add further zones to my game. Ideally I would like an arraylist for each zone, and would use the below to create each arraylist
public static ArrayList<RoomsClass> castleMap = new ArrayList<>();
The problem I now have is how to handle the player moving, initially with a single zone/arraylist I could reference that arraylist directly
public void findRoomCoords(int ID) {
for (int i = 0; i < castleMap.size(); i++) {
if (castleMap.get(i).roomID.equals(ID)) {
PLAYER.setCurrentRoomZone(castleMap.get(i).roomZone);
PLAYER.setCurrentRoomX(castleMap.get(i).roomX);
PLAYER.setCurrentRoomY(castleMap.get(i).roomY);
PLAYER.setCurrentRoomZ(castleMap.get(i).roomZ);
}
}
}
My initial thought was to use a getter/setter to remove the reference of castleMap from my movement code in order to access different arraylists, however this is where things have fallen over, I can't seem to work out how to get the arraylist name to change, depending on the outcome of the setZoneMap() method.
public void setZoneMap() {
switch (PLAYER.getCurrentRoomZone()) {
case 0: {
zoneMap = Castle.castleMap;
break;
[Code] ....
View Replies
View Related
Mar 16, 2015
I have an issue with an IndexOutOfBoundsException. I am trying to populate a db from another using arraylists and arrays. I can get the data but the program fails when trying to run the inserts. I am trying to perform SQL in batches of 5. I have added a comment to the failing line.
/*Set in code at beginning*/
ArrayList<String[]> privacyList = new ArrayList<String[]>();
ArrayList<String[]> statementBuffer = new ArrayList<String[]>();
/*Some sql is performed and the following String array is populated*/
while (rs.next()) {
String[] row = new String[55];
resultSetIsEmpty = false;
row[0] = rs.getString("ID");
[Code] ....
View Replies
View Related
Dec 7, 2014
I have a class with static ArrayLists to hold objects such as Members,Players etc.I want to save the class with the arrays so as to reload them again and hold onto the list of objects within those ArrayLists.
The ArrayClass
import java.io.Serializable;
import java.util.ArrayList;
public class ArrayClass implements Serializable {
[code]....
The arrays within the ArrayClass are empty when i reload the application.I cant tell if the arrays are being properly saved or is it in the reloading from file???
View Replies
View Related
Mar 13, 2014
Its supposed to notify the user if they have a palindrome, but keeps returning true even when I type, "hello".
import java.util.Scanner;
public class PalinDrome {
public static void main(String[] args) {
String line;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a word ");
[code]....
View Replies
View Related
Feb 25, 2014
Having two values
<c:set var="var1" scope="view" value="#{ID1}"/>
<c:set var="var2" scope="view" value="${ID2}" />
I tried in <c:if test=${var1 == var2}>
and eq also
above condition is not working. Both are same object. How to check?
View Replies
View Related
Jul 23, 2014
I'm trying to get the input of two jcomboBoxes for example if jcombobox 1 option 1 and jcombox box 2 option 1 is selected result = x
Here is my code:
comboDest1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo box.
//
JComboBox comboDest1 = (JComboBox) event.getSource();
[Code] ....
How would i achieve this?
View Replies
View Related
Jun 17, 2014
how can i compare date with following request the value date transction must be within the Active date(>= greater than or equal) and inactive date(<= less than) date range
View Replies
View Related
Jun 17, 2014
how can i compare two double values is this correct
Java Code:
public boolean isEqualToD(double s_src, double s_compareTo)
{
boolean flag = false;
try
{
if(s_src == s_compareTo)
{
flag = true;
[code]...
View Replies
View Related
Feb 3, 2014
I have the following method stubs to complete:
public class Item{
private int myId;
private int myInv;
public Item(int id, int inv){
myId = id;
myInv = inv;
[Code] .....
I do not understand how to complete the compareTo() method and the equals() method. I understand that the compareTo() to should return 1 if the argument is smaller -1 if its bigger and 0 if they are the same, but I do not understand how it's possible to compare the current object with the object passed in as the parameter.
This is what I tried for the compareTo():
public int compareTo(Item other){
return this.compareTo(other);
}
But my compiler tells me its a recursive call so I am not sure if I am doing this correctly.
Basically I am supposed to compare an object to another but I am not sure how to access the object that is not passed in as a parameter and compare it. Same goes for the equals(). This is what I tried for that (compiler also says its a recursive call):
public boolean equals(Item other){
return this.equals(other);
}
View Replies
View Related
Feb 10, 2009
how do i compare string in if else ?
cos if i do these, it get an error of
Comparing string using == or !=
if(carModel == "Honda") {
car.setCarID(1);
car.setCarModel("Toyota");
car.setCarDescription("Powered by VVTi Engine");
car.setCarTransmission("Auto");
car.setCarPrice(56000);
View Replies
View Related
Apr 26, 2015
Circle class:
public class Circle extends GeometricObject implements Comparable<Circle>
{
private int radius;
public Circle(int newRadius)
{
radius=newRadius;
[Code] ....
When I run the driver class it tells me that all tests have passed(as it should be) except for Test 0. I have tried to play around with the code, but I cant figure it out and it is driving me crazy because in my head my code makes sense.
View Replies
View Related
Feb 18, 2014
how can i compare two date in between in java
View Replies
View Related
Mar 15, 2015
I have a ArrayList of objects of class called HockeyPlayer (ArrayList<HockeyPlayer>). A HockeyPlayer has a String name and int number of goals.
This is my current work for comparing each object in the list to every other and printing them to screen:
Iterator<HockeyPlayer> it = hockeyPlayersList.iterator();
while (it.hasNext()) {
HockeyPlayer singleHockeyPlayer = it.next(); //the first one encountered
// HockeyPlayer nextHockeyPlayer = it.next(); //the next one encountered
[Code]...
This of course produces some duplication in the print-out: These are the equal hockey players: Who Ever wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
Jason Harrison wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
These are the equal hockey players: Jason Harrison wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
Who Ever wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
How do I remove the duplication in the print-out?
View Replies
View Related
Dec 24, 2014
I need to compare an int with an array of values generated with a for loop previously. I have something like that for the search..
for( int i = 0; i < 5; i++){
System.out.print("Indovina.. inserisci un valore: ");
// I memorize the value taken input
n = sc.nextInt();
[Code] ....
Also, I need to print the array each time I insert a value that is in the array. But, hiding the values still not "guessed".
View Replies
View Related
May 20, 2015
I am trying to compare the first characters of two strings.
import java.util.Scanner;
public class testIf {
public static void main (String [] args) {
String userInput = "";
char firstLetter = '-';
[Code] .....
in the if statement i get this error Cannot invoke charAt(int) on the primitive type char...
View Replies
View Related