Accessing an array java - java

for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
}
I used this code to store the strings from a dictionary array into an array containing strings with a shorter word length. I now want to pass this array alongside a random number to the following method(to create a randomly generated word):
randomWord(smallWordDictionary, outcome);
When I use the following method:
static void randomWord(String [] array, int number){
System.out.println(array[number]);
}
The console prints out null and I'm not sure why. How can I get the console to print out a string that corresponds to its element within the smallWordDictionary array?

You're not storing anything in smallWordDictionary[i] when the length is more than maxWordlength.
The default value for your array members is null, not empty string. (The default value for any array members of reference type is null.)
Consequently, some of your random indices will point to an array member that is still null.
Solutions include:
Build a smaller array, that includes only the words that passed. No nulls will be present.
Place empty string in each member that does not pass.
Check for null when printing.
Build a smaller array
The easiest way to do this is with a List.
List<String> smallWordList = new ArrayList<>;
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordList.add( dictionary.words[i] );
}
}
smallWordDictionary = smallWordList.toArray( new String[] );
Note that count is the sames as smallerWords.size() or smallerWordDictionary.length.
Place empty string in each member that does not pass
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
else {
smallWordDictionary[i]="";
}
}
Check for null when printing
static void randomWord(String [] array, int number){
String member = array[number];
System.out.println( (null == member) ? "" : member);
}

Related

Copy of variable in for-each loop?

I'm under the impression that the variable in for-each loop would get the value copied from the elements from the array. E.g.:
String[] strs = new String[] {"a", "b"};
for (String s : strs) {
s = "c";
}
for (String s : strs) {
System.out.println(s);
}
The above code has nothing to do with the original array strs and thus the output is still:
a
b
This is expected as the variable s in the for-each loop is actually a copy of the element. However, if I define my own class along with assignment constructor, the behavior changes:
class Node {
public Node(Integer value, String str) {
value_ = new Integer(value.intValue());
str_ = new String(str.toCharArray());
}
public Node(Node node) {
this(node.value(), node.str());
}
public Integer value() { return value_; }
public String str() { return str_; }
public Integer value_ = 0;
public String str_ = "null";
}
Node[] my_list = new Node[] {new Node(1, "a"), new Node(2, "b")};
for (Node n : my_list) {
n.value_ = 3;
n.str_ = "c";
}
for (Node n : my_list) {
System.out.println(n.value() + " " + n.str());
}
The output now is:
3 c
3 c
which means the variable n in the for-each loop is not a copy of the element but a reference.
Anyone can help explains why the behavior of for-each loop on String and my own class Node is inconsistent?
Thanks!
The value of the variable in the for-each loop is a copy of the values you are iterating on.
Remember that Java has two types of values: primitive values and reference values. Reference values are pointers to objects.
In the first example, s = "c" makes the variable s point to a new object. Since s is a local variable within the loop, there is no effect you can observe from the outside.
In the second example, n.value_ = 3 first finds the object that n points to: remember that n is a reference value, it's a pointer to an object. Then it goes and changes the value of field value_ within that object. These objects exist outside of the loop, so this change can be seen from the outside.
See also the very similar discussion on how the reference vs value semantics affect values passed to methods at Is Java "pass-by-reference" or "pass-by-value"?
In the first example, as you rightly pointed out, you are iterating through the str array and then setting the value to c. You are however not setting the value 3 to the str array. You can set the value to c by making the below changes to your first example.
`for (int i = 0;i<strs.length;i++) {
strs[i] = "c";
}`
This in effect is changing the value of the str array.
However in the second example you are making changes to the variables of the object passed in the for loop. Therefore the variables inside the object changed (in effect, you set the value to the objects variable)

Return specific value from a 2D array

I'm trying to figure out a way to return the value from a specific position inside a 2D array in JAVA. I've been searching for hours. I might be tired, or using the wrong terms but I can't find anything useful so far...
So for example I have a variable "a" and I want it to receive the value that is contained at a specific array position.
So for example, I want the value contained at the position :
array[1][1]
To be saved into the variable "a". Any way to do this? Btw it's a 9x9 array so it contains 81 different value but I only need 1 specific value out of the array at a time.
Thanks in advance!
You just assign the value from the array as desired:
public class Foo {
public static void main(String[] args) {
int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
int a = arr[1][1];
System.out.println(a);
}
}
// outputs : 5
Note that if a value hasn't been put in an array position then it will be in the uninitialized state. For an int this is 0.
int[][] arr = new int[9][9];
// all values in arr will be 0
Depending on the "Object type" you would assign using Object a = array[1][1]; and you can be more specific, as in int a = array[1][1];. GL

How can I correct my method so that it removes string from array?

I am trying to create a method that searches through the 'data' array to find the parameter 'elt'. If it exists, the method deletes it. I cannot figure out how to delete the string "elt". Below is what I have so far.
public class Bag<T> implements Iterable<T> {
private final int MAXLEN = 3;
private int size;
private T[] data; // array
public T remove(T elt) {
for (T word : data) {
if (word == "elt")
data = data.remove(word);
}
}
}
The error I get is "Cannot remove(T) on the array type T[].
Can someone tell me how I can properly remove the string "elt" from the array?
data is an array so you cannot remove it in the sense you are trying to do.
You have a few options:
Set the element to null
(1) and move the other elements down
Use a Collection (such as ArrayList) - then you can remove as you'd like
Option (3) would be the simplest. If you are required to use an array, (1) would look something like:
for (int i=0; i<data.length; i++) {
if ("elt".equals(data[i]) {
data[i] = null;
}
}
You can't "remove" a value from an array: you cannot change the number of elements in the array once it has been created.
You can, however, change the value of an element, e.g. setting it to null. In order to do this, you'd need the index of the element, so you can't use an enhanced for loop.
If you want a variable-size container, use a mutable List, e.g. ArrayList. You could then simply use list.remove("elt"), no explicit loop required.
Aside: use "elt".equals(word) instead of word == "elt".

Null Pointer Exception in Java when using String Arrays

I have a piece of code where the program compares the value of two arrays of strings. I am getting a java.lang.NullPointerException, even though I initialized both arrays. Here is the relevant code:
String[] functions=new String [inputs+1];
int funCounter=0;
for (int a=0;a<2;a++)
{
for (int b=0;b<2;b++)
{
if (tokenizedString[b].equals(keywords[a])&&keywords[a].equals("add"))
{
System.out.println("Yay");
functions[funCounter]="add";
funCounter++;
}
}
}
This is where I inialize tokenizedString:
String[] tokenizedString;
tokenizedString=new String[2];
tokenizedString is added to a Scanner in stream here:
StringTokenizer st = new StringTokenizer(input," ");
And here is where I initialize keywords:
String[] keywords;
keywords=new String[2];
Any ideas? Thanks!
While you are accessing tokenizedString[n], the string array will give you the nth element. If the nth element is not initialized, for object arrays it will be defaulted to null.
A better way to avoid null checks in this case will be to switch places of the string values if you are sure that the other one will never be null. So instead of:
tokenizedString[b].equals(keywords[a])
use:
keywords[a].equals(tokenizedString[b])

returning arrays in java?

In my program I am trying to return the prevScore[i] and the prevScoreName[i]. However, both return statements have errors stating that they're incompatible types (required int[], found int). I feel like it may be how I defined them in the main project (first 2 lines below). Any help would be appreciated.
prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);
public static int[] scoreChange (int prevScore[], int score)
{
for (i=1; i<prevScore.length;i++){
prevScore[i] = score;
}
return prevScore[i];
}
public static String[] nameChange (String prevScoreName[], String newName)
{
for (i=1; i<prevScoreName.length;i++){
prevScoreName[i] = newName;
}
return prevScoreName[i];
}
If you want to return just one item from each function, change the return types to int and String (not int[] and String[]). If you want to return whole arrays, then change the return statements to return prevScore; and return prevScoreName; (without the [i]).
Note that there's no need to return the whole array - the caller already has a reference to it. Just change the return types to void, delete the return statements, and get rid of the assignments in front of your calls.
You are not returning the arrays:
return prevScoreName[i]; // Returns the String at index 'i'
return prevScore[i]; // Returns the integer at index 'i'
If you want to return actual arrays, you need to lose the [i]:
return prevScoreName; // Returns the array
return prevScore; // Returns the array
Additionally, there is no need to even return anything:
prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);
You are modifying the contents of these arrays with the function calls.
It seems like you maybe don't understand arrays.
When you say
public static int[] you are making reference to an entire array. (not all of its contents, but rather you are pointing to the space in memory where the array lives.)
When you say
public static int you are referring to just one integer.
In your method, you declared your return type as int[], which meant you were returning an entire array of integers. But your return statement was trying to return prevScore[i], which is a single integer, that just happens to be contained in the array. It would have been the same if you had wrote:
int var = prevScore[i];
return var;
Its easier to see that you are returning an integer in this example.
An array of integers is not the same as an integer, so your compiler didn't know what to do when you tried to send back a single integer when it was expecting to see an array of integers.

Categories