Why can't I print the String out of my multidimensional-Array? - java

I've read in other posts, that instead of writing just System.out.println(finalPressedKey);
you should write System.out.println(Arrays.toString((finalPressedKey)); because otherwise it will just return the location where the String is saved (as far as I understood it).
public static String PressedKey[] = new String[2000];
public static String[][] finalPressedKey = {{ "", "", "", "", "", "", "", "", "", "", "", "" }}; // 12
public static String FPK3;
public static void upcounter(KeyEvent e) {
for (int x = 0; x < PressedKey.length; x++) {
if (PressedKey[x] != null && PressedKey[x + counter] != null) {
//FPK counter is supposed to be a line, and counter is where the words are supposed to be saved
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
System.out.println(Arrays.toString(finalPressedKey));
}
}
Whenever I Press a Button, it should be saved in my PressedKey Array, and finalPressedKey is supposed to contain itself, and PressedKey (also , only the last element of the array is supposed to be printed), but instead it just prints [[Ljava.lang.String;#76f42c4b]
I also tried using Arrays.deepToString(); but it gives me the same output as with Arrays.toString();
Thanks for your help!

A String[][] is not a 2-d array. It is an array of String[]. The difference is subtle but important.
The method Arrays.toString() takes an array, iterates through its elements, calls toString() on all of them, and adds a prefix, suffix, and delimiters. Since you give it a String[][] (an array of String[]), it will do the following:
Iterate through the elements (each of them a String[])
call toString() on each element - giving the default toString() value of an array - i.e. its memory address (not really but for this purpose it doesn't matter)
concatenate
Luckily for you, there is an easier way - just use Arrays.deepToString(). This behaves as you would expect.

I did not understand the whole code, but following statement is very suspicious:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
since it is adding an array (finalPressedKey[...]) to a string (PressedKey[...]), which will result in that strange text - the standard textual representation of an array (returned by toString). (from a mathematical point of view, it's strange to have 2 indexes )2D_ before the assignment and only one on the right side (1D) for same matrix)
I'm not sure, since we cannot see what counteris, but I believe you wanted something like:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter][counter] + PressedKey[x + counter];
that is, an additional [counter] on second line.
This can also be written as
finalPressedKey[FPKcounter][counter] += PressedKey[x + counter];

If you only want to store lines of strings, a normal String[] is good for you
finalPressedKey[FPKcounter] += PressedKey[x + counter];
even though I wouldn't recomment doing this, no matter what you're trying to accomplish, since this will create a new String object each time a key is pressed.
Maybe ask the question differently and tell us what you're trying to do. I guess String arrays might not be the way to go.

You have to print the elements of your array with
for(int i = 0; i<finalPressedKey[0].length; i++){
for(int j=0; j<finalPressedKey[1].length; j++){
System.out.println(finalPressedKey[i][j]);
}
}
if I understand it correctly.

Related

Can't figure out why I am getting null values

The program is supposed to print out the amount of times each name has been selected (this is indicated by number of asterisks (*). I have most of the code working but for some reason the output contains two null values for each name and I am not sure how to fix the problem. Also if you have the time, I'm also struggling to find out which name has the most amount of asterisks. Here's an example output:
1: nullnull************************ Conner
2: nullnull********************************** John
etc...
(it does this for all 10 names)
public class RandomStudentsLab {
public static void main(String[] args){
//create an array with 10 students
String [] StudentList = new String[10];
String [] StarString = new String[10];
String [] FinalString = new String[10];
//add 10 names to the student list
StudentList[0] = "Conner";
StudentList[1] = "John";
StudentList[2] = "Alex";
StudentList[3] = "Robert";
StudentList[4] = "James";
StudentList[5] = "Carl";
StudentList[6] = "Sarah";
StudentList[7] = "Bob";
StudentList[8] = "Ethan";
StudentList[9] = "Chris";
//loop 250 times selecting each student randomly
for(int i=0; i<250; i++){
int randomNum = (int)((Math.random()*10));
for(int x=0; x<10; x++){
if(randomNum == x){
StarString[x] += "*";
}
}
}
for(int z=0; z<10; z++){
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
}
}
}
Elements in FinalString and StarString arrays are still not initialized. So with += operator its calling toString on the null element and prefix "null" to each string.
As mentioned by Karthik in his answer you never initialized (as in you never assigned values) the FinalString array. That is what is causing your error.
You can easily tell since your System.out.println() is printing:
Number : nullnull Stars Name
So clearly your issue is with FinalString, it is the only variable not printing correctly.
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
You are making the same mistake with the StarString array. You are lucky enough to get away with it in this case since you end up adding variables to StarString in your loop.
However, NOT initialising ANY variable is >>horrible<< practice. You never know what was previously stored in memory, this could lead to your variables being assigned some 'alien' data that was leftover on the memory by some other program. Secondly, and this is the issue in your question, if you forget to initialise you can run into null errors and such.
So as a matter of good coding practice always initialise your variables to something. Even if you are using the variable two lines later - it doesn't matter. When you create your variable assign it a value:
If it's an integer then 0 or -1. It's better if it's a value that won't occur in your program, so if you have an error in your code you can spot it easily because your integer will be -1 instead of x y z.
If it's a string then name it 'banana' or 'peanuts' or whatever.
If it's an object make sure you initialise all of the attributes
And so on...
P.S. Not sure if I came accross as harsh, but it's absolutely not my intention. Good coding practices are simply important and will be extremely helpful in the future.
Best of luck!
EDIT:
Little update to reflect your comment on another answer.
When you create FinalString here String [] FinalString = new String[10]; your are not assigning any values to it, unlike what you did with the names.
So when your code gets to the final for loop here:
for(int z=0; z<10; z++){
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
}
}
}
And you try to do a System.out.println() for FinalString[z], well FinalString[z] still does not have a value. At no point in your code did you write
FinalString[0] = "Banana";
So obviously it will print null instead.

Read an element of an array whilst containing various data

I am currently seeking for a bit of help with the use of arrays. Quite a newbie on the Java language, so excuse the poor etiquette towards the programming format and I forwardly thank for any answers provided.
My current quarrel with the Array is how to fetch data from any array element. Currently I use the method System.out.println(Arrays.toString(listarray)) but the problem with this method is that it's not necessarily User friendly and it can't be formatted (to my little knowledge). So I'd like to ask help on how to fetch data from an element of an array and put it in a way so its readable by any given user.
Here is the code I'm utilizing:
import java.util.Arrays;
import java.util.Scanner;
public class principal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Array Example");
String[] listarray = new String[10];
int i = 0;
byte op;
do {
System.out.println("Select your option:");
System.out.println("1-Add");
System.out.println("2-Check");
System.out.println("3-Change");
op = input.nextByte();
switch (op) {
case 1:
input.nextLine();
System.out.println("First String:");
String a1 = input.nextLine();
System.out.println("Second String:");
String a2 = input.nextLine();
System.out.println("Third String:");
String a3 = input.nextLine();
System.out.println("(" + (i + 1) + "/10)");
listarray[i] = a1 + a2 + a3;
i++;
break;
case 2:
System.out.println(Arrays.toString(listarray));
break;
}
}while(op != 9);
}
}
While the code does work, I'd like to know how to format the data, and from a single element, not every element. Or even if I can. Thanks and I appreciate the time spent reading this question.
You have two questions:
How do you reference an array element?
How do you format output?
When you declare an array like
String[10] names;
You have an array that can hold 10 strings, numbered 0 to 9. To reference the fifth element (remembering that array indices start at 0), you would use
names[4]
You can do various things with a reference. If you put it on the right side of an equals sign, then you are assigning the value at that element to something else.
currentName = names[4];
If you put it on the left side, you are assigning something to that element.
names[4] = "Michael";
And if you put it in a println statement, it will output the value to wherever the println statement is putting things at that time, usually the console:
System.out.println(names[4]);
So much for references. And, incidentally, that's what it is called -- you are referencing the 5th element of the array, or you are referencing the indicated element of the array. You can also put the number in a variable:
var i = 4;
System.out.println[i];
Note that most of these uses of the reference assume there is something IN that element of the array. Until something is assigned there, the element is a null.
To format, I recommend looking (carefully) into the Format / Formatter classes and choosing some simple things to do what you want. As an example, you could have:
String formatString = "The name is currently %s.";
String outputString = String.format(formatString, names[i]);
and String's format method will substitute whatever is in names[i] for the %s in the format. There are also formats for ints, doubles, and dates.
For more info, see the Oracle Tutorial on arrays and on manipulating Strings.
Hope that helps
If you want to traverse the Array that is how you can do it:-
for(int i = 0; i < listArray.length; i++) {
System.out.println(listArray[i]);
}
or
for (String s : listArray) {
System.out.println(s);
}

I have an Array which i Want to Strip and Convert to another array

I have an array(2 field array) which i want to Strip "/" off the first field and retrieve the remaining array With its same 2nd field value...
This is what i'm trying to do..
CurrencyPairs = new string[] { "EURUSD", "USDJPY", "GBPUSD", "EURGBP", "USDCHF", "AUDNZD", "CADCHF", "CHFJPY", "EURAUD", "EURCAD", "EURJPY", "EURCHF", "USDCAD", "AUDUSD", "GBPJPY", "AUDCAD", "AUDCHF", "AUDJPY", "EURNOK", "GBPCAD", "GBPCHF", "NZDJPY", "NZDUSD", "EURNZD", "USDNOK", "USDSEK", "XAUUSD", "XAGUSD", "XTIUSD", "XBRUSD" };
This Array Will be passed from a C# App to my Java App Which Will then create a Integer ID for the whole Strings...
Now,
I want to Split the third String "EUR" "USD" into two and add "/" to it...
Which Will look like this:
ReceivedPairs = new string[] { "EUR/USD", "USD/JPY", "GBP/USD", "EUR/GBP", "USD/CHF", "AUD/NZD", "CAD/CHF", "CHF/JPY", "EUR/AUD", "EUR/CAD", "EUR/JPY", "EUR/CHF", "USD/CAD", "AUD/USD", "GBP/JPY", "AUD/CAD", "AUD/CHF", "AUD/JPY", "EUR/NOK", "GBP/CAD", "GBP/CHF", "NZD/JPY", "NZD/USD", "EUR/NZD", "USD/NOK", "USD/SEK", "XAU/USD", "XAG/USD", "XTI/USD", "XBRUSD" };
And, the Java append a value to the Arrays by making it look this way..
func(String Pairs, int Id);
func("EURUSD",928);
Which One Pair Will always be attached to a Generated ID..
How do I Split the Pairs Into two?
How do i Still make the values not leave the Array after the Splitting?
Thanks for your time taken..
EDIT: I have Tried currencyPairs.strip, but that won't work as i have no value to strip in the Strings... There is no "/", no "-". Just Splitting By Substring Length is what i need.. I know that in C++, but here in Java... Missing
If you're using Java 8, you can do something like this:
String[] CurrencyPairs = new String[] { "EURUSD", "USDJPY", "GBPUSD", "EURGBP", "USDCHF", "AUDNZD", "CADCHF", "CHFJPY", "EURAUD", "EURCAD", "EURJPY", "EURCHF", "USDCAD", "AUDUSD", "GBPJPY", "AUDCAD", "AUDCHF", "AUDJPY", "EURNOK", "GBPCAD", "GBPCHF", "NZDJPY", "NZDUSD", "EURNZD", "USDNOK", "USDSEK", "XAUUSD", "XAGUSD", "XTIUSD", "XBRUSD" };
String[] ReceivedPairs = Arrays.stream(CurrencyPairs)
.map(s -> s.substring(0, s.length()/2) + "/" + s.substring(s.length()/2))
.toArray(String[]::new);
Or a plain old for loop if you don't want to use streams:
ReceivedPairs = Arrays.copyOf(CurrencyPairs, CurrencyPairs.length);
for(int i = 0; i < ReceivedPairs.length; i++)
ReceivedPairs[i] = ReceivedPairs[i].substring(0, ReceivedPairs[i].length()/2) + "/" + ReceivedPairs[i].substring(ReceivedPairs[i].length()/2);

Explain how this permutation works

I searched a code for permutation in java:
public class MainClass {
public static void main(String args[]) {
permuteString("", "String");
}
public static void permuteString(String beginningString, String endingString) {
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0, i) + endingString.substring(i + 1);
permuteString(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
I can't understand it even though I know it was only a basic code. I want someone to explain it to me to make it clearer. Thank you guys
One can construct a permutation, by picking items from a bag repeatedly and thus constructing a sequence. For a string, the bag is a collection of characters. We can use a String to represent this.
If we thus want to construct a random permutated string, we first look if the bag is empty. In the above code, the bag is the endingString and the emptiness check is done with:
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
As you can see the check does not look whether the bag is completely empty: from the moment the string has only one character (one element), it is evidently we will pick that one. So we pick it and print it after the sequence we've already constructed.
Problem: a problem with this approach is that if we want to list the permutations of the empty string (there is exactly one: the empty string), one will get errors.
Now we need the iterative case. Remember that beginningString stores the sequence we've constructed up till now and endingString stores the list of characters we still can pick from. Now a way to pick is to select a valid index i in the endingString. The character at that index is then picked.
We update the sequence (beginningString by simply appending the character that was placed at i, thus:
beginningString + endingString.charAt(i)
In order to update the bag, it means that the bag now contains all the characters before the index, and the ones after the index. This is formalized as:
String newString = endingString.substring(0, i) + endingString.substring(i + 1);
newString is here the new bag. We can then do the recursive call to pick the next item from the bag. So for a given index i, in order to pick and call recursively, the code reads:
String newString = endingString.substring(0, i) + endingString.substring(i + 1);
permuteString(beginningString + endingString.charAt(i), newString);
Now since we wish to enumerate over all possible permutations, we loop over all possible indices for i. Since we do this recursively as a consequence, we will enumerate all permutations.

strange problem in an array

I'm working on a little server app with Java. So, I'm getting informations from different client, and if information comes in, the following method is called:
public void writeToArray(String data) {
data = trim(data);
String[] netInput = new String[5];
netInput[0]="a";
netInput[1]="a";
netInput[2]="a";
netInput[3]="a";
netInput[4]="a";
netInput = split(data, ",");
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]); // THIS LINE KICKS OUT THE ERROR.
if(pos_arr >0 && pos_arr<100) {
fernrohre[pos_arr] = rohr_value;
println("pos arr length: " + fernrohre[pos_arr]);
println("pos arr: " + pos_arr);
}
The console on OS X gives me the following error:
Exception in thread "Animation Thread"
java.lang.ArrayIndexOutOfBoundsException:1
at server_app.writeToArray(server_app.java:108) at server_app.draw(server_app.java:97)
at processing.core.PApplet.handleDraw(PApplet.java:1606)
at processing.core.PApplet.run(PApplet.java:1503)
at java.lang.Thread.run(Thread.java:637)
As you can see, I tried to fill the array netInput with at least 5 entries, so there can't be an ArrayIndexOutOfBoundsException.
I don't understand that, and I'm thankful for your help!
It would work already for me, if I can catch the error and keep the app continuing.
You put 5 Strings into the array, but then undo all your good work with this line;
netInput = split(data, ",");
data obviously doesn't have any commas in it.
In this line
netInput = split(data, ",");
your array is being reinitialized. Your split method probably returns an array with only 1 element (I can guess that data string doesn't contain any ",").
Update
The split() method is custom, not String.split. It too needs to be checked to see what is going wrong. Thanks #Carlos for pointing it out.
Original Answer
Consider this line:
netInput = split(data, ",");
This will split the data string using comma as a separator. It will return an array of (number of commas + 1) resulting elements. If your string has no commas, you'll get a single element array.
Apparently your input string doesn't have any commas. This will result in a single element array (first element aka index = 0 will be the string itself). Consequently when you try to index the 2nd element (index = 1) it raises an exception.
You need some defensive code,
if(netInput.length > 1)
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]);
You make
netInput = split(data, ",");
and
split(data, ",");
returns one element array
You are re-assigning your netInput variable when the split() method is called.
The new value might not have an array count of 5.
Can you provide the source for the split() method?

Categories

Resources