My string keeps initializing itself as null... or at least it seems that way. I am trying to make a custom toString function for my matrix. this.matrixArray is a 2D array of dimensions 'm x n'.
public String toString() {
String stringAsMatrix = "";
String dimensions = this.m + "," + this.n + "\n";
stringAsMatrix += dimensions;
String[] dataRows = new String[this.m];
for (int row = 0; row < this.m; row++) {
for (int column = 0; column < this.n; column++) {
String elementString = "";
elementString += this.matrixArray[row][column];
if (column == this.n-1) {
dataRows[row] += elementString + "\n";
} else {
dataRows[row] += elementString + ","; // Only add a comma if this isn't the last element in the row
}
}
stringAsMatrix += dataRows[row];
}
return stringAsMatrix;
}
This is the output I get but I don't understand why it prints 'null' before my string. The dimensions are correct (the matrix array is indeed 2x2). The values themselves are also correct (my matrix is {{1,2}, {3,4}})
2,2
null1.0,2.0
null3.0,4.0
dataRows[row] += elementString + "\n";
dataRows[row] is starting out with null in it. So it becomes
dataRows[row] = null + elementString + "\n"
...which is exactly what you get. Instead, write
dataRows[row] = elementString + "\n";
Related
I'm trying to remove the last char in the string using substring method.
Outside the if statement works normally. But inside it just goes through the if statement and returns original String.
public String getElkon(int p, int zbytek) {
System.out.println(zbytek);
for (int i = 0; i < p; i++) {
vysledek += elkon[i];
vysledek += " ";
System.out.println(vysledek);
}
***if(zbytek != 0){
vysledek = vysledek.substring(0, vysledek.length() - 1);
return vysledek;
}
else{
return vysledek;
}***
}
Your code would be more straightforward if you didn't have to trim the trailing space from appending your String(s). Also, it isn't clear why you expect zbytek to control the trim. I think you wanted if (p != 0) (since that is your loop sentinel). I would use a StringJoiner to implement this like
public String getElkon(int p, int zbytek) {
System.out.println(zbytek);
StringJoiner sj = new StringJoiner(" ");
for (int i = 0; i < p; i++) {
sj.append(elkon[i]);
}
return sj.toString();
}
The last character in the string is a space, since you added it last time in the for loop.
To trim the last space before if statement you could use the code
public String getElkon(int p, int zbytek) {
System.out.println(zbytek);
for (int i = 0; i < p; i++) {
vysledek += elkon[i];
vysledek += " ";
System.out.println(vysledek);
}
if (p > 0)
vysledek = vysledek.substring(0, vysledek.length() - 1);
if(zbytek != 0){
...
}
return vysledek;
}
I want to append certain string in the last item of the foreach array.
The program works perfectly fine. Given the items in the "pending" array, it should append the out value in the last item in the pending value:
String a = out + "-" + rptdate + "-";
for (String pn : pending) {
//checks if total value + pending length value is less than 160
if (a.length() + pn.length() < 160) { // < to leave room for the comma as well
if (a.length() != 0) {
if (a.length() != 14) {
a += ",";
}
}
a += pn;
} else {
resultingStrings.add(a);
a = pn;
Log.d("messages", a);
}
}
resultingStrings.add(a);
for (String r : resultingStrings) {
sendSMS(r);
}
Try simple code
int size = pending.size();
int index = 0;
for (String pn : pending) {
if(index == size - 1){
// it is last foreach => add your last string here
}
index++;
...
}
Hope this help
You could also do,
for(int i = 0; i < array.length; i++) {
if(i = (array.length - 1)) {
//this is the last element in the array
}
}
If all you need to do is grab the last element of a Collection and append some text to it then this should work.
String out = "Some value";
int lastIndex = pending.getSize() -1; // < 0 indexed
String lastItem = pending.get(lastIndex)
String newLastItem = lastItem + out; // < String concatenation
but from your snippet I don't think that's what your after because if we remove some of the magic numbers and correct the indentation, and make some assumptions about what your trying to do your left with
String a = out + "-" + rptdate + "-";
int prefixLength = a.length();
for (String pn : pending) {
//checks if total value + pending length value is less than 160
if (a.length() + pn.length() < MAX_LENGTH) { // < to leave room for the comma as well
if (a.length() > prefixLength) {
a += ",";
}
a += pn;
} else {
// have string longer than max length, so save and start a new sms.
resultingStrings.add(a);
Log.d("messages", a); // < log a before you overwrite it.
a = pn;
}
}
// DO YOU WANT TO APPEND out AS A SUFFIX TO a HERE ???
// a += out;
// but if so youll want to consider the case if a is now > MAX_LENGTH
resultingStrings.add(a); // add the last string
// send all composed strings
for (String r : resultingStrings) {
sendSMS(r);
}
I am picking your relatively new to coding so I'd suggest first you start off with some pseudo-code of what your trying to do, it can then become comments in your code. Always keep your code formatted nicely so that indents are matched, and use descriptive names for your variables, and constants.
I want to take the following matrix below and rearrange the chars TOAD to ADOT and the rearrange the corresponding columns below to where the char above moved, so for example A moved to col 0 so now VGD should all be in col 0 etc.
TOAD is a separate array by the way! im using that keyword to sort the martrix alphabetically.
//Matrix output and then the code.
T O A D
V V V X
D V G G
D F D V
public String printMatrix(String s [][]){
char key[] = polyCipher.getKeyword().toCharArray();
String keyOut = "";
for(int i=0;i<key.length;i++){
keyOut += key[i] + " ";
}
keyOut += "\n";
for (int i = 0; i < s.length; i++) {
// keyOut += PHRASE_KEY[i] + " ";
for (int j = 0; j < s[i].length; j++) {
keyOut += s[i][j] + " ";
}
keyOut += "\n";
}
return keyOut.toUpperCase();
}
public static String [][] buildMatrix (String translation, String outermarker, String innermarker) {
// outerdelim may be a group of characters
String [] sOuter = translation.split("[" + outermarker + "]");
int size = sOuter.length;
// one dimension of the array has to be known on declaration:
String [][] result = new String [size][size];
int count = 0;
for (String line : sOuter)
{
result [count] = line.split (innermarker);
++count;
}
return result;
}
public void sortArray(){
// do tomorrow
}
public String matrixFormatter(String x){
String resultstr = "";
int i = 0;
while(i < x.length()) {
// If end of string: only add character.
if (i == x.length() - 1) {
resultstr += x.substring(i, i + 1);
} else {
if ( ((i + 1) % 4) == 0) {
resultstr += x.substring(i, i + 1) + "|";
} else {
resultstr += x.substring(i, i + 1) + ",";
}
}
i++;
}
return resultstr;
}
}
I want to compare two Strings in two different arrays. Strings are stored in s1 and s2 variables. This part works great, but if I add if condition, if(s1.equals(s2)){/*...*/}, I get ArrayIndexOutOfBoundsException.
Look at these two screen shots:
In both cases arrays have same values. The only thing that was changed is the if condition.
Image#1
Image#2
Code:
Vagon tmp = first;
int stevec = 1;
while(tmp != null){
double trenutenVolumen = 0;
for(int j = 0; j < tmp.opisTovora.length; j++){
trenutenVolumen += tmp.volumenTovora[j];
}
double lahkoDodamVolumna = tmp.volumen-trenutenVolumen;
double lahkoDodamTeze = lokomotiva.najvecjaMasa-trenutnaTeza;
System.out.println("len: "+tmp.opisTovora.length);
if(tmp.tipTovora == tipTovora[0] && lahkoDodamVolumna >= volumenTovora[0] && trenutnaTeza+tezaTovora <= lokomotiva.najvecjaMasa){
if(!tmp.tipTovora){
String s1 = tmp.opisTovora[0];
String s2 = opisTovora[0];
//if(s1.equals(s2)){
System.out.println(s1 + " == " + s2);
System.out.println("LAHKO DODAM TOVOR #" + (i+1) + " => V VAGON #" + stevec);
break;
//}
}
if(tmp.tipTovora){
System.out.println("LAHKO DODAM TOVOR #" + (i+1) + " => V VAGON #" + stevec);
break;
}
}
stevec++;
tmp = tmp.next;
}
Your exception is on this line - String s1 = tmp.opisTovora[0]. It means that tmp.opisTovora is an empty array, so tmp.opisTovora[0] is out of the bounds of that array.
It has nothing to do with equals.
I want to write a toString method for a Matrix class where I need to return a formatted string which contains the matrix. The entries in the matrix are very different in length so just separating the entries with a TAB doesn't the trick. Right now I have the following:
public String toString(){
String str = "";
for(int i=0;i < _dim[0];i++){
for(int j=0;j < _dim[1];j++){
str += this.values[i][j] + "\t" + "\t";
}
str += "\n";
}
return str;
}
Which gives me something like this.
3.2004951E7 -1.591328E7 17839.0
-35882.0 17841.0 -20.0
1794.0 -892.0 1.0
Is there a way to print these properly aligned without knowing in advance how long each entry is going to be?
Thanks.
Is there a way to print these properly aligned without knowing in
advance how long each entry is going to be?
I don't think there is any built-in library function available which can do such things
for us. We will have to make our own formatting such as, using: %-xs:
Create an one dimensional array: maxWidth[col] to find the maximum width of each column: the column size is equal to the number of column of the 2D array.
Visit the 2D array to find the maximum width of each column
create the formatting string for each column using "%-"+maxWidth[col]+"s ", where - after the % specifies formatting for left-justified.
Please check out the formatting Numeric Print Output for more details.
The sample code:
String data[][] = {{3.2004951E7+"" , -1.591328E7+"", 17839.0+"" },
{-35882.0 +"" , -17841.0+"", -20.0+"" }};
int col = data[0].length;
int row = data.length;
int maxWidth[] = new int[col];
for(String[] rowD : data)
for(int i=0; i< col; i++)
{
if(maxWidth[i] < rowD[i].length())
maxWidth[i] = rowD[i].length();
}
String format = "";
for(int x : maxWidth)
format += "%-"+(x+2)+"s ";
format +="%n";
System.err.println(format);
for(String[] rowD : data)
{
System.out.printf(format, rowD);
}
Output:
3.2004951E7 -1.591328E7 17839.0
-35882.0 -17841.0 -20.0
You can use String.format() if you know the length of your longest String, let's call it maxLength.
public String toString(){
String str = "";
for(int i=0;i < _dim[0];i++){
for(int j=0;j < _dim[1];j++){
String value = String.valueOf(this.values[i][j]);
str += String.format("%1$-" + (max-value.length()) + "s", " ") + value + "\t";
}
str += "\n";
}
return str;
}