toString java of arrays - java

I have several arrays in a class
I want to implement toString() to print all values.
How to do this?
public String var1[];
public int var2[];
public String var3[][];
public int var4[];
public int var5[][];
public String toString() {
for(String s : var1) {
System.out.println(s.toString());
}
return null;
}
That prints all var1[] content but how to print all?? Do I have to put a loop for every one of them?

You can use the Arrays.toString() static helper method as follows:
String lines[] = getInputArray();
System.out.println(java.util.Arrays.toString(lines));

I think what you are looking for is Arrays.deepToString()
Refer to this link for more details. It takes an array and calls toString() on every element.

First of all, it depends on the size of your arrays. You did not mention any size for each of it. Of course, we can use for each. The second question obviously, how to want to print them all in the screen. that is the matter.
In case, if you go with normal for loop [ex: for(int i=0;i<ar.length();i++)] in this case. You have to go by individual loop for each array.
If your array size is same for all. You can simply use one loop to iterate all of them to print it off.
Hint: don't forget to handle the ArrayOutofBound exception. You would need that :P

String someArray = new String[] {"1", "2"};
String toString = Arrays.asList(someArray).toString();
The code above will print out the toString in a more readable format:
[1, 2]
If you are using JDK 1.5, you can use:
String[] strings = { "ABC", "DEF" };
String s = Arrays.toString(strings);

Related

Return inside a method one or two arrays

Its not duplicated i have read all and nothing suite in my case so please read it and answer it.I have two arrays.One is Vehicle and the other is pin.This is a part of code and it is only the method.
First question :
if i have declare the arrays on the same main out of
this method the way i pass them on the method is right?With other words the parameteres
are good or need (int vehicle[],int pin[]) or something else?
Second question +=
i dont know what it does but i think that in the array pin it takes
as an ecample the pin[1] cost has 10.The number 10 is taken by
getcostosvehicle();(we put it from userinput) so when the array fills
and it hasnt any slot then the costs will be finished.As a result will
have lets say the ended slot is 20 in pin[20] lets say it has 350.The
return statement will give us only the last cost?It would be better to
write return pin[i]; so in that way it will return all the pin with
the whole costs of each one slot,am i right?
Third question
On this code and that i want to write me as an answer could you return
two arrays?I mean return pin[i],vehicle[i]; not only return pin[i];.If
yes,could you do an answer and doesnt need to fill in the vehicle
array.Just to show me if this can happen.
public static int getallcosts(vehicle[],pin[]) {
int costos = 0;
for(int i =0; i < pin.length; i++) {
costos += pin[i].getcostosvehicle();
}
return costos;
}
if i have declare the arrays on the same main out of this method the way i pass them on the method is right?With other words the parameteres are good or need (int vehicle[],int pin[]) or something else?
I'm not sure I understand you correctly but of course getallcosts(vehicle[],pin[]) won't compile, i.e. you need to define the type of the arrays (or the names if vehicle and pin would actually be the types).
It would be better to write return pin[i]; so in that way it will return all the pin with the whole costs of each one slot,am i right?
No, you can only have one return value. If you want to return multiple values then you need to wrap them in an object (array, list, pojo, etc.).
On this code and that i want to write me as an answer could you return two arrays?
See the part above: if you want to return multiple arrays you need to add them so some object and return that object. Since you didn't provide the types for the arrays I'll use another example:
class Result {
String[] strings;
int[] numbers;
}
Result someMethod() {
Result r = new Result();
r.strings = new String[]{"a","b","c"};
r.numbers= new int[]{1,2,3};
return r;
}
First question:
If you are calling a method (so you're not defining it) yuo can write parameters as you do, without type.
Otherwise you need to specify type. In this case you are defining a new method so you need to specify type of parameters.
Second question:
'+=' it's like write
costos = costos + pin[i].getcostosvehicle();
So you will add to the current value of 'costos' the 'costos' of vehicle retrieved by 'getcostosvehicle()';
Third question:
As i know you can't return two Objects of any type in return statement.
So you'll need to reorganize your code to do operation first on an array and return it and then on the other one and return it.
For example you can do a method that have as parameter a generica array do some logic inside and then return it. You will call this method for the first array and then for the second.
Example:
public int[] method(int[] array){
/*do something
*/
return array;
}
Then you will call:
firstArray = method(firstArray);
secondArray = method(secondArray);
If you want more, or i have to change something comment please.

Cannot invoke indexOf on an Array of strings?

I'm writing a method to calculate the distance between 2 towns in a given array by adding all the entries between the indexes of the two towns in the second array, but I can't invoke indexOf on the first array to determine where the addition should start. Eclipse is giving me the error "Cannot invoke indexOf on array type String[]" which seems pretty straight forward, but I do not understand why that won't work.
Please note the program is definitely not complete.
public class Exercise_3 {
public static void main(String[] args){
//Sets the array
String [] towns={"Halifax","Enfield","Elmsdale","Truro","Springfield","Sackville","Moncton"};
int[] distances={25,5,75,40,145,55,0};
distance(towns, distances, "Enfield","Truro");
}
public static int distance(String[] towns,int[] distances, String word1, String word2){
int distance=0;
//Loop checks to see if the towns are in the array
for(int i=0; i<towns.length; i++){
if(word1!=towns[i] || word2!=towns[i] ){
distance=-1;
}
//Loop is executed if the towns are in the array, this loop should return the distance
else{
for(int j=0; j<towns.length; j++){
*int distance1=towns.indexOf(word1);*
}
}
}
return distance;
}
}
No, arrays do not have any methods you can invoke. If you want to find the index of an given element, you can replace String[] by ArrayList<String>, which has an indexOf method to find elements.
It doesn't work because Java is not JavaScript.
The latter offers an array prototype that actually exposes the function indexOf, while the former does not.
Arrays in JavaScript are completely different from their counterparts in Java.
Anyway, you can be interested in the ArrayList class in Java (see here for further details) that is more similar to what you are looking for.
How about this (from this post)?
There are a couple of ways to accomplish this using the Arrays utility class.
If the array is not sorted:
java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search for performance:
java.util.Arrays.binarySearch(theArray, o)
I hope this helps you. If it doesn't, please downvote.

Surround string with another string

I there any utils method in Java that would enable me to surround a string with another string? Something like:
surround("hello","%");
which would return "%hello%"
I need just one method so the code would be nicer then adding prefix and suffix. Also I don't want to have a custom utils class if it's not necessary.
String.format can be used for this purpose:
String s = String.format("%%%s%%", "hello");
No but you can always create a method to do this:
public String surround(String str, String surroundingStr) {
StringBuffer buffer = new StringBuffer();
buffer.append(surroundingStr).append(str).append(surroundingStr);
return buffer.toString();
}
You have another method of doing it but Do not do this if you want better performance:-
public String surround(String str, String surroundingStr){
return surroundingStr + str + surroundingStr;
}
Why not use the second method?
As we all know, Strings in Java are immutable. When you concatinate strings thrice, it creates two new string objects apart from your original strings str and surroundingStr. And so a total of 4 string objects are created:
1. str
2. surroundingStr
3. surroundingStr + str
4. (surroundingStr + str) + surroundingStr
And creating of objects do take time. So for long run, the second method will downgrade your performance in terms of space and time. So it's your choice what method is to be used.
Though this is not the case after java 1.4
as concatinating strings with + operator uses StringBuffer in the background. So using the second method is not a problem if your Java version is 1.4 or above. But still, if you wanna concatinate strings is a loop, be careful.
My suggestion:
Either use StringBuffer of StringBuilder.
Not that i know of, but as already commented, its a single line piece of code that you could write yourself.
private String SurroundWord(String word, String surround){
return surround + word + surround;
}
Do note that this will return a New String object and not edit the original string.
Create a new method:
public String surround(String s, String surr){
return surr+s+surr;
}
Tested the following and returns %hello%
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(surround("hello", "%"));
}
public static String surround(String s, String sign) {
return sign + s + sign;
}
StringUtils.wrap(str,wrapWith) is what you are looking for.
If apache common utils is already a part of dependency, then you can use it. Otherwise as others already mentioned. It's better to add to your base. Not a big deal
https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/StringUtils.java

Split method of String class returns a string?

According to the String.split() documentation the method returns array, so how come the following code compiles?
The retval variable inside the for loop is a String and not an array but there is no error?
public class String_Splitting_Example
{
public static void main(String args[])
{
String Str = new String("Welcome-to-Tutorialspoint.com");
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-"))
{
System.out.println(retval);
}
}
}
String.split() returns an array. It isn't assigning the result of the call to retval (notice there's no = assignment operator). Instead, the : notation means it's using a for-each loop to iterate over the array, and assigning each element in turn to retval.
As #nobalG points out there are a number of good resources on StackOverflow as well. Check out some questions tagged java and foreach.
As Jared Burrows commented, by writing for (String retval: Str.split("-")) you are iterating through each part of the array where retval contains the current String in the array of Strings you got from doing Str.split

Array is not displaying correct values

I am new to java,I have created array which accepts 8 values. It's working fine,also accepting values but it's not displaying correct output on console,please help me what the problem can be ??
Here's my code,
import java.util.*;
public class array2
{
public static void main(String []args)
{
Scanner scan=new Scanner(System.in);
int[] nums=new int[8];
for(int count=0;count<8;count++)
{
nums[count]=scan.nextInt();
}
System.out.println(nums);
}
}
Use System.out.println(Arrays.toString(nums)); (import java.util.Arrays to do this)
If you just say System.out.println(nums);, it will only print the object reference to the array and not the actual array elements. This is because array objects do not override the toString() method, so they get printed using the default toString() method from Object class, which just prints the [class name]#[hashcode] of the object instance.
Printing an array like that is not possible in Java, you probably got something like "[I"...
Try looping:
for (int n=0; n<nums.length; ++n)
System.out.println(nums[n]);
This is because you are printing the array object instead of elements
Use this
for(int i : nums){
System.out.println(i);
}
The [ symbol in the output indicates that the object being printed
is an array.
Alternatively, you can do
System.out.println(Arrays.toString(nums));. This gives String representation of the array.
Display array in a loop:
for(int count=0; count<8; count++)
{
System.out.println(nums[count])
}
You are printing array reference, not their elements.
You need to use Arrays.toString(int[]), to create string that will contain the expected from. Currently you are printing string representation of array itself.
nums[count]=scan.nextInt() will only print the memory location of the array and not the array contents. To print the array contents you need to loop as you did when you insert them. I would try:
for(int count=0;count<8;count++){
System.out.println(nums[count]);
}
Hope that helps

Categories

Resources