I am trying to write a searching algorithm to check one node in a linked integer list vs another node in that same list.
I think there seems to be a problem with the IF statement (data is in the list):
LinkedList<Integer> listScore = new LinkedList<Integer>();
int temp = 0;
String temp2 = "";
boolean flag = true;
while (flag){
flag = false;
for (int j = 0; j < linebr; j++){
if (listScore(j) < listScore(j+1)){
System.out.println("Testing");
}
}
I did originally try listScore[j] but I think there is something wrong with the way I have written it. Any help or explanation as to why it doesent work would be Greatly appreciated!!
Instead of listscore(j) and listscore(j+1), what you need to get values inside LinkedLists is .get(). So you should be using listscore.get(j) and listscore.get(j+1).
Im trying to make every "ADJEKTIVER" strings in the storyList array into random strings from my adjectivesList array. When I'm trying to compile, I only get the error: cannot find symbol- variable. With .length as the variable/attribute. Been searching for a solution quite a while now
ArrayList<String> storyList = new ArrayList<String>();
storyList = reader.getWordsInFile(storyFilename);
ArrayList<String> adjectivesList = new ArrayList<String>();
adjectivesList = reader.getWordsInFile(adjectivesFilename);
for (int index =0; index < storyList.length; index++)
{
storyList[index] = storyList[index].replace("ADJEKTIV", adjectivesList[random.nextInt(adjectivesList)]);
}
writer.write(adjectivesList, outputFilename);
use storyList.size() method instead of storyList.length
for (int index =0; index < storyList.size(); index++)
Arralist or List doesnt have any property named "length". use size() method instead
Arrays have a public final int property called length, that holds the number of elements in the array, arrays can't change how many elements they have in Java.
Which brings me to ArrayList having a collection that can change the number of elements it has is useful, but it's not magic(I would've liked someone to tell me this). It has an Array of type E[] I will call this internal array arr.
When you push an element to an ArrarList
public boolean add(E e) {
E[] temp = new E[this.arr.length];
for (int i = 0; i < this.arr.length; i++)
temp[i] = this.arr[i];
this.arr = new E[this.arr.length + 1];
for (int i = 0; i < this.arr.length; i++)
this.arr[i] = (i == temp.length ? e : temp[i]);
temp = null; // free temp or let it fall out of scope
return true;
}
// Removing is easy too
public E remove(int index) { // I'm just doing the first of the overloaded methods, in api
E returnValue = this.arr[index];
E[] temp = new E[this.arr.length - 1];
for (int i = 0; i < this.arr.length; i++)
if (i != index) temp[i] = this.arr[i];
this.arr = new E[this.arr.length - 1];
for (int i = 0; i < this.arr.length; i++)
this.arr[i] = (i == temp.length ? e : temp[i]);
temp = null; // free temp or let it fall out of scope
return returnValue;
}
The being able to change the length forces it to be accessed in a dynamic way in Java via a method called size in this case.
public int size() {
return this.arr.length;
}
Java exists both as a standard and as an implementation, the former might be implemented such that Strings are mutable so making String have a length method makes code more compatible between the implementations of the standard, as implementations(not necessarily those of Java) have been known to deviate, so making them more compatible makes sense for the Java devs.
As for why ArrayList uses size() as the method name, while String uses length(), and Array uses length, I don't know although in my opinion(warning opinions ahead) it's not unreasonable that accessing the lengths got implemented the way they did, and the Java devs felt locked in, because changing the spec would also required changing the code in question.
public int length() {
return this.arr.length;
}
All code shown is merely for demonstration purposes, and comes as is, and is without warranty of any kind.
I am using arraydeque to store another arraydeque of type Integer.
My code looks like this:
private ArrayDeque<ArrayDeque<Integer> > grid;
public void initiateGrid(){
for (int i = 0; i < Length; i++)
{
ArrayDeque<Integer> columns = new ArrayDeque<Integer>();
for (int j = 0; j < Width; j++)
columns.add((int)(Math.random() * 100));
grid.add(columns);
}
}
When I try to run this it gives me a NullPointerException on grid.add(columns).
does anyone know what am I doing wrong?
Also if there is a better way to do this, please let me know.
Thanks
initialize grid, because you cannot use a null object, otherwise you get NullPointerException
public void initiateGrid(){
grid = new ArrayDeque<ArrayDeque<Integer>>();
//...
}
I'm in dire need of help with this project. I'm trying to implement a Bag class for a programming assignment, and I'm getting hung up on the addAll(), Union(), and equals(), methods.
Edit: According to the assignment, addAll() is supposed to add all of the the objects from the second array into the first. I'm no longer getting an error when I run it, but for some reason it will not add all of the elements from the second array, it will only add the first 2. Thanks guys, this one is working perfectly now!
Edit: For Union(), I'm supposed to create a third bag that will contain all the contents of the first 2 bags. I was getting an ArrayIndexOutOfBoundsException when running this method. I've updated the code following biddulph.r and it's also working great. Thanks again!
Edit: "First attempt" And for equals(), it's supposed to check the size of the bags to make sure they are equal in size, then check to see if they contain the same numbers. So as it's written now, my equals() method will compare sizes and return the boolean value for that, but I'm unsure of how to make it compare the actual values.
import java.util.Arrays;
import javax.swing.*;
public class bag {
int maxSize = 10; //Size of the arrays
int count = 0; //Number of items stored in the array
int[] a;
int[] b;
bag c;
bag d;
public bag() {
//for(int i = 0; i < maxSize; i++){
//a[i] = (int)(1+Math.random()*100);
//}
a = new int[maxSize];
}
public String bagString() {
return Arrays.toString(a);
}
public void add(int b) {
try {
a[count] = b;
count++;
} catch (ArrayIndexOutOfBoundsException n) {
JOptionPane.showMessageDialog(null, "Array is full, element will not be added");
}
}
public void removeRandom() {
int i = (int)(1 + Math.random() * (count - 1));
a[i] = a[count - 1];
a[count - 1] = 0;
count--;
}
public void remove(int b) {
for (int i = 0; i < maxSize; i++) {
if (contains(b)) {
a[i] = a[count - 1];
}
}
}
public boolean isEmpty() {
if (count == 0) return true;
else return false;
}
public boolean contains(int b) {
int tf = 0;
for (int i = 0; i < maxSize; i++) {
if (a[i] == b) tf = 1;
}
if (tf == 1) return true;
else return false;
}
public int size() {
return count;
}
public void addAll(bag c, bag d) {
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
}
public void union(bag c, bag d) {
bag bigger = new bag();
for (int i = 0; i < c.size(); i++) {
bigger.add(c.a[i]);
}
for (int i = 0; count < d.size() - 1; i++) {
bigger.add(d.a[i]);
}
System.out.println(bigger.bagString());
}
public boolean equals(bag c, bag d){
if(c.size() != d.size()){
return false;
}else{
for(int i = 0; i < c.union(c, d).size(); i++){
if(c.union(c, d).contains(c.a[i]) && c.union(c, d).contains(d.a[i])){
return true;
}
}
return false;
}
}
}
I really appreciate any help you guys can give me, thanks.
EDIT: Thanks to everyone for your help, you guys are life savers.
Your problem for addAll() is here
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
You shouldn't be adding elements until your c bag becomes bigger than d, you should be adding all of d's elements to c.
for (int i = 0; i < d.size(); i++) {
c.add(d.a[i]);
}
So the part of the assignment you are having issue with is:
public void addAll(bag c, bag d){
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
}
which you say is supposed to add all of the the objects from the second array into the first.
If you break that down and apply it to your addAll() method, it sounds like you are supposed to be adding all of the items in bag "d" into bag "c".
Your for loop is saying start i at 0, and add 1 to it until the size of c is less than or equal to d.
What it should be saying is start i at 0, and add 1 to it until you have gone through every item in d.
That would look like this:
for (int i = 0; i < d.size(); i++){
c.add(d.a[i]);
}
i is increased every time you go through the for loop, and i will stop increasing when you have got to the size of d (the second condition). At this point you will exit the for loop. You don't have to worry about the size of c.
In fact you can probably get rid of the if (a.length >= c.size() + d.size()) line as well.
I hope my explanation helps you understand why the changes have been made to the method.
I think you have a lot of problems with the design of the class that you should address first. If you are representing the bag as a static or dynamic array then you only need one array, not 2. You also don't need two bags inside each bag as attributes, that doesn't make any sense; all you should have left is the size of the bag or count and the array to hold all the elements (which are integers in your case). Also, avoid naming parameters for functions and attributes for the class the same way. Not doing so might confuse the compiler and will require code like self.attributeName to use attributes; otherwise, the compiler assumes you're talking about the parameter.
If you make these changes, the rest should be straight-forward from here. Since it's an assignment, you should make these changes and try again because you won't learn if we provide the answers for you; you'll see it will be much easier once you structure it correctly.
P.S. it's a convention to start a class name with a capital letter. Bag and not bag
addAll
There's a couple of problems with this function as written. First is that it's confusing to the caller. The code using this method would be something like this:
Bag bag1 = ...
Bag bag2 = ...
Bag bag3 = ...
bag1.addAll(bag2, bag3)
...or perhaps bag2.addAll(bag2, bag3). The function is intended to add elements from one bag in to another bag, so why does the caller have to specify three different bags? There's only two involved. You should either make the function static, so it can be called like Bag.addAll(bag1, bag2) or (better) make it totally clear who's getting elements added by making it take a single argument bag1.addAll(bag2).
Second problem is that the function isn't implemented correctly, but I think that's because you're getting confused because you've got three bags involved instead of two. To sketch out how it should be fixed:
Bag target = ...
Bag source = ...
if (target.a.length >= target.size() + source.size()) {
for (int i = 0; i < source.a.length; i++) {
target.add(source.a[i]);
}
}
Good variable naming is your friend.
union
You haven't specified what problem you're having with your implementation, so I'm not going to simply rewrite it for you. Edit your question with the problem, and I'll help.
However, this is an excellent example of a method that should be static (a Factory method, in fact). It should be able ot be called like: Bag biggerBag = Bag.union(bag1, bag2).
EDIT after his comment regarding the .union problem
The problem with .union is that you're looping through each bag using some else's size. It boils down to, if you want add each element from source in to target, you should be only counting elements from source, as so:
bag bigger = new bag();
for (int i = 0; i <= c.size(); i++) {
bigger.add(c.a[i]);
}
note that your method does not protect against the bigger bag not being big enough. You should have a check to make sure that it is BEFORE the loops, or even better just create a big enough bag.
equals
Again, you need to show that you've tried to write it, and then ask a question specifying what you need help with. Update your question and I'll help.
Your method:
public void addAll(bag c, bag d) {
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
}
betrays your lack of understanding of Object Oriented programming.
Remember that the method addAll() is already acting on a bag, and so you should not need to specify 2 bags in the arguments.
Calling example:
mybag.addAll(yourBag);
would demonstrate a possible usage - it would add all contents of yourBag into myBag.
I'll give you this method for free (assuming that the array 'a' contains the contents of the bag - something I'm not sure about because your variable names aren't clear):
public void addAll(Bag otherBag) {
for (int i : otherBag.a) {
add(i);
}
}
The above method will copy all contents of otherBag into this bag.
Another thing I noticed - you also have a b[] instance variable - what's that for?
You also have 2 other bag instance variables. Not sure why.
I have a method called public int getSize() and it is suppose to return the number of items in the list. the instance variable is private Listable[] items; I thought it would just be something like this:
int size = 0;
for (int i = 0; i < items.length; i++){
size++;
}
return size;
But when I run it through these tests I get this nullpointerexception on the for (int i = 0; i < items.length; i++){ line
I don't think it likes items.length for some reason. I'm not getting any errors in Java. How should I do this?
i already tried return items.length;
that didnt work either.
http://www.easywayserver.com/blog/java-how-to-get-size-of-list/
I saw this article when I was browsing the web it contains the code that implements the list.size() method.
List<String> ls=new ArrayList<String>();
ls.add("one");
ls.add("Three");
ls.add("two");
ls.add("four");
int sizeOfList=ls.size();
System.out.println("Size of List :"+sizeOfList);
I believe you forgot to initialize the variable. Try something like:
items = new Listable[10];
For your getSize() method, you just need to return items.length
As MeBigFatGuy has commented (+1) your items variable is null. In fact, his comment entirely answers your question... Here's an implementation that should do what you want:
public int getSize() {
return items == null ? 0 : items.length;
}