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.
Related
Can I re-declare an Array that is already declared?
So I am trying to go through a LinkedList and get every index which includes "null" as an Element and add those indexes to an array of ints.
The problem I have is : The array is already declared as:
int[] solution = new int[0];
Can i redeclare it once again like lets say:
int newSize = 10;
solution = [newSize];
Does that work?
int k = 0;
int counter = 0;
if(!isEmpty())
{
for(int j = 0 ; j < size(); j++)
{
if(current.getContent().equals(null))
{
counter++;
}
}
result = new int[counter];
for(int i = 0 ; i < size(); i++)
{
if(current.getContent().equals(null))
{
result[k++] = i ;
}
}
}
I tried printing out the elements of Result but all i get is well... an empty array.
Short answer (as mentionned on java documentation => link)
The length of an array is established when the array is created. After creation, its length is fixed.
Some more details:
When you use :
int[] solution = new int[0]
you create an array that can hold 0 element and ask "solution" to refert to it.
If later on your code you use solution = new int[10] you will create an array that can hold 10 elements and ask "solution" to refer this new array.
The previous array still exists somewhere in the memory.
Search for "java memory management" if you want a full explanation.
I have a JLabel array that starts with an integer number of elements. How can I remove an certain number of elements from the array? For example, every time the int is updated:
int i = 21;
i = i - removedElements
How can I update the array to contain that many elements, instead of creating an entirely new array with the desired number of elements?
As others have already mentioned, List is the way to go here since it is specifically designed for adding and or deleting elements.
However if you would prefer to use the JLabel Array you already have in established then you will need to realize that the only way to delete an element from that array is to actually create another array with the desired element to delete excluded from it then return it into the original array. Below I have supplied a simple method named deleteJLabelFromArray() that can do this for you:
public static JLabel[] deleteJLabelFromArray(JLabel[] srcArray, int... indexesToDelete) {
int counter = 0;
JLabel[] newArray = new JLabel[srcArray.length - indexesToDelete.length];
for (int i = 0; i < srcArray.length; i++) {
boolean noGo = false;
for (int j = 0; j < indexesToDelete.length; j++) {
if (i == indexesToDelete[j]) { noGo = true; break; }
}
if (noGo == false) { newArray[counter] = srcArray[i]; counter++; }
}
return newArray;
}
With this method you can delete whatever indexes you supply within the indexesToDelete argument (delimited with a comma). Copy/Paste the code into your project then you can use it something like this:
JLabel[] jla = {jLabel2,jLabel3,jLabel4,jLabel5};
jla = deleteJLabelFromArray(jla, 2);
for (int i = 0; i < jla.length; i++) {
System.out.println(jla[i]);
}
In this example we are going to delete the element number 2 (remember that arrays are 0 based) and therefore jLabel4 would be removed from the Array.
Keep in mind that this would be scary stuff with really big arrays.
Hope this helps.
I am looking to verify if all of the integers in a 2d array are unique, return true if they are unique otherwise false.
The below code is what I have for a simple array. But I am not sure how to go about modifying it.
public boolean verifyUniqueIntegers(int array []){
boolean result = true;
for (int i = 0; i < array.length; i++) {
if(array[i] <= 0 || array[i] > n*n){
result = false;
}
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
result = false;
}
}
return result;
}
The best way to approach this problem is to use a mathematical construct called a set. The key property of a set for your purposes is that they can not contain duplicates by definition. Java provides a data structure allowing us to create sets found in java.util.Set. This is the generic interface that specifies how sets should behave. However, interfaces provide only specification, not implementation, so you'll have to use Set in conjunction with another class java.util.HashSet, which implements Set. You seem like a novice programmer, so I wrote a test program to show you how this works.
import java.util.*;
public class SetTest {
public static void main(String[] args) {
int[] set = {1,2,3,4,5,6,7};
int[] nonSet = {1,2,3,4,5,4};
System.out.println(verifyUniqueIntegers(set));
System.out.println(verifyUniqueIntegers(nonSet));
}
public static boolean verifyUniqueIntegers(int[] array) {
Set<Integer> set = new HashSet<Integer>();
for(int i : array) // This is a construction called a for-each loop
if(!set.add(i)) // This is an example of what's called autoboxing
return false;
return true;
}
}
Here I've used a static method for convenience, but you can of course change this into an instance method for your purposes once you give it a try.
First, I create a for-each loop to iterate over all the elements in the array that's passed into verifyUniqueIntegers(). For each loops use what are called iterators to create a reference to each element, one at a time, and make it available in the body of the loop. When the end of the body is reached, the for-each loop automatically resets i to the next element in the array, as long as there are elements left in the arry. You can ready more about for-each loops in the Oracle Java Tutorials.
Then, the method calls set.add(i). This attempts to add i to the set that we previously defined. This is an example of what's called autoboxing. Since the Set interface is generic, it can contain elements of any object type. Since int is a primitive, we must use the wrapper class Integer to specify the elements in our set. When we call set.add(i) you don't have to convert the int into an Integerbecause the java compiler does it for you.
This method returns true if i is not a duplicate, then adds it to the Set. It returns false if i is a duplicate and does nothing. Thus, we can take advantage of the method check the uniqueness of each element in your array. The method returns false as soon as a duplicate is found, and otherwise returns true. Hope this helps, good luck!
Your algorithm is slow. To make it faster, you should use something like HashMap.
Create empty HashMap<Integer>.
Iterate on all 2d-array elements (for-for loop).
For every element check if your HashMap contains it.
If yes then return false, it means that not all elements in your array are unique.
If no, add element to HashMap.
After for-for loop return true.
As a beginning programmer, choose basic solutions without the sophistication of more complex parts of the library that do in truth offer more power. The main thing for you here is to learn how to use 2D arrays.
You can do it very simply because of the hidden specification that you did not mention but is in the code. None of the numbers can be greater than N * N.
Start with pseudo-code. The basic algorithm is to have a checking array of length N * N. Put a marker in each element as you find the number in the source array, using the number as the index into the checking array. If there is already an element there, then the number is not unique. The code becomes something like this:
final int N = 10; // Your choice of N, or perhaps input it.
int [][] needsChecking = new int [N] [N]; // fill it up.
public boolean arrayIsGood (int [][] src) {
final int N2 = N * N;
boolean [] checker = new boolean [N2];
for (int i = 0; i < N2; i++) { // Initialize Checker
checker [i] = false;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int value = src [i][j];
if ((value <= 0) || (value > N2))
return false;
if (checker [value - 1]) // already found
return false;
checker [value - 1] = true;
} // for j
} // for i
return true; // if we get here every element has passed.
} // arrayIsGood (int [][])
Some of the other answers are more elegant or more extensible or handle space usage better or may find the result faster, etc. But master the basics first.
public boolean verifyUniqueIntegers(int array []){
Set<Integer> set = new HashSet<>(array.length);
for (int i : array)
{
if (set.contains(i))
return false;
set.add(i);
}
return true;
}
or maybe:
public boolean verifyUniqueIntegers(Integer array []){
return new HashSet<>(Arrays.asList(array)).size() == array.length;
}
I need a method to delete a determinate element from a handmade list.
I have a class called AudioFile. Each element of the list is an object from this class.
Then, I have the class FileTable, with this atributes:
private AudioFile[] table;
private int size;
I defined this method, but It doesn't work when I call it:
public void deleteFile(AudioFile file){
AudioFile[] table2 = new AudioFile[100];
int j = 0;
for (int i = 0; i < size; i++){
if (table[i] != file){
table2[j] = table[i];
j++;
} else {
i++;
}
}
for (int k = 0; k < size); k++){
table2[k] = table[k];
}
table[size-1] = null;
}
I think the code it's easy to understand, but if you don't understand something or you need some more information about the class AudioFile, you can say it and I'll try to help too. Thank you!
You're reinventing the wheel, just use a Collection like a List or a Set. They have already a remove() method that does exactly what you want to do.
See Arrays as a low level type and always use Collection (except in really specific cases).
i have this script, but i can't increment
LinkedList<Card> deckOfCards = new LinkedList<Card>();
for (int count = 0; count < deckOfCards.size(); count++) {
deckOfCards[count].add(new Card(Rank.values()[count % 13].toString(),Suit.values()[count / 13].toString(), number[count % 13],Image[count % 52]));
}
i get an error on deckOfCards[count], so my doubt is how i can do this
(The type of the expression must be an array type but it resolved to LinkedList)
i previous code is an array, and works
deckOfCards = new Card[number_cards];
for (int count = 0; count < deckOfCards.length; count++) {
deckOfCards[count] = new Card(Rank.values()[count % 13].toString(),Suit.values()[count / 13].toString(), number[count % 13],Image[count % 52]);
}
}
//suppose to get na name, value of card, but the result is [null, null, null, etc]
public Card[] giveCardPlayer1() {
String name1 = Arrays.toString(deckOfCards);
nameF = name1;
String suit_1 = deckOfCards.toString();
suit1 = suit_1;
return deckOfCards;
}
public int totalValuePlayer1() {
return currentTotal1;
}
public String name1() {
return nameF;
}
public String suit_1() {
return suit1;
}
thanks!!!!
Just call deckOfCards.add(...).
You can't index a Java List the same way you would an array. You have to use its add() method instead. This appends the specified element to the end of the list.
There is also another add() method which takes an int index parameter. However, since lists are not of fixed size, you can't just directly set the nth element of the list by calling deckOfCards.add(count, new Card(...)) - you need to ensure first that the specified element exists in the list, otherwise you get an IndexOutOfBoundsException. It is also worth mentioning that accessing linked lists by index is a slow operation (compared to e.g. ArrayLists) for any list of nontrivial size.
Update
Ah, and you need to fix your loop invariant too. The current version
for (int count = 0; count < deckOfCards.size(); count++) { ...
will never execute the loop body, since the initial size of your list is 0. Change it to
for (int count = 0; count < number_cards; count++) { ...
In addition to Peter's post; if you need to index a list like you try to do here, you can use ArrayList instead.