array output not correct - java

I am using 2 classes and a bunch of methods to store something in an array then writing it to a file. After I write something to a file, instead of being of the var double,
this is my code:
public void storeArray(Quest1 a, Quest2 b, String filename) throws FileNotFoundException{
PrintWriter k = new PrintWriter(filename);
for(int i = 0; i < a.getDays(); i++)
{
k.println(b.storeArr(a));
}
k.close();
System.out.println("Written.");
}
Quest 1 is a class, Quest 2 is a class and String filename is just getting passed through.
After doing all that and putting the Quest3 object in my main menu.
I run the program, input all my values etc which get put into an array in the class Quest 2 and then I write them to a file.
I open that file to check if it has worked and i get this:
[D#264532ba
How do I fix that to get my double variables in the file?

Print out Arrays.toString instead of just print out the array (which invokes its toString inherited from Object):
k.println(Arrays.toString(b.storeArr(a)));
Or if you want some custom format, you can use StringUtils.join from Apache Commons. Or, perhaps just write a loop if you cannot use any dependencies.
The thing you output is the toString of the array, which is its type ([D) + # + its hash code (264532ba).

Arrays use the default implementation of toString() and that's why the output of the array is:
[D#264532ba
You have two options to print an array's content:
Iterate over each element.
Use Arrays.toString(array).
Explanation of the weird output
Let me explain the following code:
double[] array = new double[10];
System.out.println(array);
array is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The array's toString() is similar to Object's toString():
getClass().getName() + "#" + Integer.toHexString(hashCode());
So the output would be something like:
[D#756a7c99
where [ represnts the depth of the array, and D refers to double. 756a7c99 is the value returned from hashCode() as a hex number.
Read also Class.getName() JavaDoc.

if storeArr returns an Array, you could use Arrays.toString(b.storeArr(a))

This here:
k.println(b.storeArr(a));
You are printing b.storeArr(a) which is an array object.
Just do this:
PrintWriter k = new PrintWriter(filename);
for(int i = 0; i < a.getDays(); i++)
{
b.storeArr(a);
k.println(Arrays.toString(b));
}

Related

How can I use printf to print arraylist of different variables?

I have an arraylist filled with different variables. How can I print this arraylist out to the console using the printf flag in Java?
public class mendietaRAL {
public static void theArrayList() {
ArrayList<Object> theList = new ArrayList<Object>();
theList.add(123);
theList.add("Java");
theList.add(3.75);
theList.add("Summer C");
theList.add(2018);
for (int i = 0; i < theList.size(); i++) {
System.out.printf(theList.get(i));
}
theList.remove(1);
theList.remove(3);
System.out.println();
for (int i = 0; i < theList.size(); i++) {
System.out.printf(theList.get(i));
}
}
}
Use toString() method to retrieve a string represantation of the objects you want to print to the console. Read Java documentation about it here. In short here is what the method does:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
theList.get(i).toString()
This answer will also give you a bit more information.
Another thing to mention is that you were trying to use printf method to log information about an object without providing the proper method arguments. Read more about printf here. Instead what you should be doing is using println method to print your information as mentioned above in new lines, as this method does not take any arguments:
System.out.println(theList.get(i).toString());
Call toString() for each element in printf, for example.

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

how see an array in logcat for android

I would like to log raw data like arrays in my logcat, so I know what is the output.
Lets say I have an array... like that:
File[] mp3List = ...
Log.v("test", mp3List);
Why can't I just log the array to console? How can I do it?
You can't log the array because it is just an Object. LogCat has no idea how to deal with it or display it in a way you want.
If each File object has a toString() method that displays the information that you want you can use:
Log.v(Arrays.toString(mp3List));
Otherwise you'll have to concatenate your own String to log:
StringBuilder sb = new StringBuilder();
for(File f : mp3List) {
sb.append(f.getName());
}
Log.v(sb.toString());
The reason why this doesn't work is simply because the 2nd argument of Log.v is a String not a File[]. Java strictly enforces argument types.
Update:
You can easily transform the information contained a File object into a String object. All java objects implement a toString(), which if I remember correctly returns a combination of the ClassName and the address of the object is located. However this usually doesn't contain useful information. So you need to define the conversion yourself.
Now to convert from File[] to String is more complicated because you when call a method on an array it works on the array object rather than on members of an array (which contains the information I suspect you care about). So calling mp3List.toString() will return a single string that describes the array object and not the information contained in the array.
So you'll probably want to write a method like this:
String fileArrayToString(File[] f){
String output = "";
String delimiter = "\n" // Can be new line \n tab \t etc...
for (int i=0; i<f.length; i++)
{
output = output + f[i].getPath() + delimiter;
}
return output;
}
And then call make your log call as follows:
Log.v("MyTag", fileArraytoString(mp3List);
However this might be hard to read.
I personally would do it like this:
for (int i=0; i<mp3List.legnth; i++)
Log.v("MyTag", Integer.toString(i) + ":" + mp3List[i].getPath());
Its simpler, produces cleaner log messages and is easier to understand what is going on as a programmer.
If you have a String array, you can just add toString() to it and it will be displayed.
For custom objects, you should override the toString() method and print what you want to see for that object. If you then have an array, the array will be printed with the output from the toString method.
Maybe I misunderstood, but I think its simply:
string sLog = "";
for(mp3List..)
{
sLog += mp3List[i].getName();
}
Log.v(sLog);
isnT it? Because, I suppose, when you try to print an array like that you ll get a log entry saying that mp3List is an System.Blah.Blah.File[] ..
Hope it helps..
I like one liners better:
for(File file:list) Log.d(TAG, "list: " + file.getPath());

How to print the strings in an array?

At the moment I have an array of
public Module[]moduleArray = new Module[4];
and to output it i'm using
public void displayModules()
{
for (int i = 0; i < moduleArray.length; i++)
{
System.out.println(moduleArray[i]);
}
}
However it's outputting
Module#1f5e4ae5
Module#67871079
null
null
Implement / override toString() in the Module class. When you see the Module#xyz String representation it is because the only implementation of toString() for the Module class is the Object class's implementation. Since Object doesn't know anything about Module it just outputs the class name and an instance id.
The class Module needs a meaningful toString() method. What you're seeing is the output of the default Object.toString() method. For example, if Module had String properties name and type you could have a toString method like:
#Override
public String toString()
{
return "Module named: " + name + " of type: " + type;
}
You would then see the String returned above instead of the output of the default toString method.
Overriding toString() method in array's content class, in your example Module class, will help you to print every value from array while iterating array.
There is quick way to print arrays content without iterating over array elements, convert array to list using Arrays.asList() utility method.
System.out.println("Convert Array to List " + Arrays.asList(moduleArray));

Increment last letter of a string

Here's where I wish Java's String class had a replaceLast method, bu it doesn't and I'm getting the wrong results with my code.
I'm writing a program that searches a data structure for any items that match a string prefix. However, since I'm using an Iterator, the last item returned by the iter.next() call doesn't match the pattern, so I want to change the search string so that the last character of the query is increased by one letter. My testing code is returning [C#b82368 with this code and An as titleSearch:
public String changeLastCharacter(String titleSearch) {
char[] temp= titleSearch.toCharArray();
char lastLetter= temp[temp.length-1];
lastLetter++;
temp[temp.length-1]= lastLetter;
String newTitleSearch= temp.toString();
return newTitleSearch;
}
First, what is the cause of the output from this code?
Second, is there a better way to execute my solution?
You want:
newTitleSearch = new String(temp);
The toString method is not overridden for arrays; it's the usual Object.toString, intended for debugging. The above actually creates a string of the characters. An alternative is:
int len = titleSearch.length();
String allButLast = titleSearch.substring(0, len - 1);
newTitleSearch = allButLast + new Character(titleSearch.charAt(len - 1) + 1);
Whenever you see unexpected output like ....#<hex-digits>, the chances are that you are accidentally using toString() on some object whose class inherits the default implementation from Object.
The default toString() method returns a String whose value consists of the type name for the object combined with the object's "identity hash code" as hex digits. In your case the [C part is the type name for a char[] object. The '[' means "array of" and the 'C' means the char primitive type.
The rules for forming the type names used in the default toString() method are fully documented in the javadocs for java.lang.Class.getName().
Your problem is temp.toString(). Try String newTitleSearch = new String(temp); instead.
I figured this out by System.out.println(temp[0]+","+temp[1]); after temp[1] add been assigned to the incremented value. You could do this even easier by using your IDE's debugger.
Since the array was being assigned properly, the problem had to be in the toString().

Categories

Resources