This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 2 years ago.
I am trying to print the content of a PriorityQueue to an output file by converting it to an ArrayList.
(NOTE: I'm not printing to the console!)
Besides I declared a toString method, I am still getting the outputs like this: I#7c3df479
Converting the queue to ArrayList:
private PriorityQueue<GameState> unexpanded = new PriorityQueue<>(Comparator.comparing(GameState::getF_n));
...
public ArrayList<GameState> getUnexpanded()
{
ArrayList<GameState> unExpanded = new ArrayList<>(unexpanded);
return unExpanded;
}
Getting the ArrayList and trying it to print:
private void printSolution() throws IOException
{
FileWriter outFile = new FileWriter("output.txt");
PrintWriter output = new PrintWriter(outFile);
ArrayList<GameState> unexpanded = game.getUnexpanded();
for (int i = 0; i < unexpanded.size(); i++)
{
output.printf(unexpanded.get(i).toString() + "\n");
}
output.close();
}
toString method:
public class GameState
{
private int[][] grid;
...
#Override
public String toString()
{
return "{" + grid + "}";
}
}
Everything is working fine but the program print the contents like: I#7c3df479
Can anybody please help me with this?
Many thanks for the answers and comments in advance.
'grid' is declared as a 2D array which isn't a primitive in java. As such, when you try to print it, it still prints out the memory address / reference.
Try replacing it with Arrays.deepToString(grid) instead.
Related
This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 1 year ago.
i want to call the arrays to the method and add it in a catalog but i cant print it as it shows [[Ljava.lang.String;#7ad041f3, [Ljava.lang.String;#251a69d7, [Ljava.lang.String;#7344699f] when i print it. i think its cause of the way i called the attribute title,author and genre but i dont know how to call.
import java.util.Scanner;
import java.util.Arrays;
public class Card{
String title[] = {"Hairy potter","Perck Jackson","The promised Neverland","Goosebump"};
String author[] = {"j.k.Rowling","Rick Riordan","Kaiu Shirai","R.L.Stine"};
String genre[] = {"Fantasy Fiction","Adventure","Dark fantasy","Horror fiction"};
public static void main(String[] args) {
Card obj = new Card();
String[] title1,author1,genre1;
title1 = obj.title;
author1 = obj.author;
genre1 = obj.genre;
String[][] catalog = new String[3][4];
for (int i = 0 ; i<4;i++){
catalog[0][i] =title1[i];
catalog[1][i] =author1[i];
catalog[2][i]= genre1[i];
}
System.out.println((catalog[0]));
System.out.println(Arrays.toString(catalog));
}
}
Edit:
i had to use Arrays.deepToString(catalog)
When you try to print catalog[0], it returns you the data type. Here, that is java.lang.String.
What you're looking for is:
System.out.println(Arrays.deepToString(catalog));
This will print the contents.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 5 years ago.
By way of an example I have a txt file that contains a list of dogs, one on each line of the file and then "**" on the last line. I then have the following code to load this into an ArrayList to use in a JComboBox.
This way I can simply add another line in the text box to add another dog.
My example code is as follows
public class test{
static String temp;
public static void main(String[] args) {
List<String> picklistDogs = new ArrayList<String>();
File picklistFile = new File (filePath);
try {
BufferedReader loadPickList = new BufferedReader (new FileReader(picklistFile));
while(true) {
temp = loadPickList.readLine();
if (temp != "**") {
picklistDogs.add(temp);
} else {
break;
}
}
loadPickList.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
}
catch(IOException e){
System.out.println("file io error");
}
} // END of main
} // END of class test
My problem seams to be that the if statement never triggers the break to exit the while loop.
Any solutions would be appreciated.
Use !temp.equals("**") .Try below code
if (!temp.equals("**")) {
picklistDogs.add(temp);
} else {
break;
}
In order to compare strings better to use java.lang.String#equals
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
Here is my example: I want to know if it is possible to pass an argument initialized with null, and later initialize the object with a correct value.
private class Source {
String str;
String getStringValue() {
return str;
}
void setStringValue(String str) {
this.str = str;
}
}
private class UserSource {
Source src;
UserSource(Source src) {
this.src = src;
}
String getValue() {
return src.getStringValue();
}
void setValue(String str) {
src.setStringValue(str);
}
}
Now how I'm using.
Source srcW = new Source();
UserSource userSourceW = new UserSource(srcW);
srcW.setStringValue("Second Value");
System.out.println("From UserSource:" + userSourceW.getValue());
userSourceW.setValue("Is not Second");
System.out.println("From Source:" + srcW.getStringValue());
The output:
From UserSource:Second Value
From Source:Is not Second
But, want to know if is possible to use like:
Source srcN = null; // YES I want to assign Not initialized!
UserSource userSourceN = new UserSource(srcN);
srcN = new Source();
srcN.setStringValue("First Value");
System.out.println("From UserSource:" + userSourceN.getValue());
Of course the output is
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Is there an alternative?
Unfortunately, it's not possible to do so. When the value is initially null, then you're passing the null reference. Later you initialize it with srcN = new Source();, but then you're rewriting the source.
You could work around it with a Reference<Source>. But that would only make the code more cumbersome. Moreover, the Source class is a perfect candidate to pass it as an empty source, and then initialize it later with setString().
Am I missing something? What's your problem with the code as is?
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm new in Java and I find it very complicated because of the errors that I come across with. So I have a problem with this piece of code:
Main Class:
public class Main {
public static void main(String[] args){
Answer a = new Answer();
String ans = null;
while(ans != "A"){
ans = a.create();
System.out.print(ans + "\n");
}
}
}
Answer class:
import java.util.Scanner;
public class Answer {
public String create(){
Scanner s = new Scanner(System.in);
return s.next();
}
}
I want the program to allow me to write something. Then, if what I've written hasn't been the letter A, the program must allow me to write something else, otherwise has to stop. But, even though I write "A", the program is still keeping on, allowing me to write something else. What's wrong with the code?
String can't be compared properly using the != operator. Instead you should use while(!ans.equals("A")). Secondly, try not to recreate the Scanner object in the create method. This is a resource waste.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 years ago.
Here is my code. Can someone help me with this error?
public class ExcahngeSort {
public double[] ExSort(double[] gangnam,int size)
{ double temp;
for(int outrloop=1;outrloop<size;outrloop++)
{
for (int innrloop=0;innrloop<size-outrloop;innrloop++)
{
if(gangnam[innrloop]>gangnam[innrloop+1])
{
temp=gangnam[innrloop];
gangnam[innrloop]=gangnam[innrloop+1];
gangnam[innrloop+1]=temp;
}
}
}
return gangnam;
}
}
I get an unexpected value [D#360be0printed. I don't know what this means.
Here is my main method:
public class BsortSimulate {
public static void main (String args []){
//BSort bs = new BSort();
ExcahngeSort es = new ExcahngeSort();
double gangnam [] = {12,24};
System.out.println(es.ExSort(gangnam, 2));
}
}
You are printing the array incorrectly, use Arrays.toString() utility method:
System.out.println(Arrays.toString(es.ExSort(gangnam, 2)));
Arrays in Java do not override toString(), as opposed to most List implementations.
System.out.println(Arrays.toString(es.ExSort(gangnam, 2)));
It is not an error. You are trying to print array object. You can't override toString() for arrays in Java.
Your print statement should be like below:
Example:
System.out.println(Arrays.toString(es.ExSort(gangnam, 2)));