cant print the arrays [duplicate] - java

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.

Related

Printing ArrayList to an output file [duplicate]

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.

How do I fix java.lang.ArrayIndexOutOfBoundsException: 2? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I'm writing a program which utilizes OOP. The program I am creating is supposed to recruit applicants to a team. In my Team.java, I created a method which is supposed to accept members and add it to the team. This is a snippet of my code:
public int maxMembers;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[maxMembers] = newMember;
memberCount++;
}
I have tried this code but the line,
members[maxMembers] = newMember;
keeps throwing an error java.lang.ArrayOutOfBoundsException: 2
I have tried using a for loop in adding a new member but it does not do what I expected. Can anyone assist me in finding a solution?
You have to assign maxMembers a value in the first line, otherwise your array will have 0 elements.
public int maxMembers = 10;
Firstly, you did not initialize the variable maxMembers.Also, in the code, the line members[maxMembers] = newMember; would always put your entry in the end of the array, I think thats not the intended use of your method, public void addMember(Member newMember)
Rewriting your method would look like,
public int maxMembers=somePositiveInteger;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[memberCount] = newMember;//here
memberCount++;
}
Initialize the array with a value so that number of elements in array can be decided.

Intro to Java Error: cannot find symbol - Class ArrayList [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 4 years ago.
this is my first time taking a programming language. Why is BlueJ giving me an error for both ArrayList? I want to test my inputs so that if they are in the arraylist it will return true, otherwise it will return false? Step 2 of this will be using a for loop.
private boolean isValidProvince(String province)
{
ArrayList<String> provinceList;
provinceList = new ArrayList<String>(10);
provinceList.add("British Columbia");
provinceList.add("Alberta");
provinceList.add("Saskatchewan");
provinceList.add("Manitoba");
provinceList.add("Ontario");
provinceList.add("Quebec");
provinceList.add("Newfoundland");
provinceList.add("Prince Edward Island");
provinceList.add("Nova Scotia");
provinceList.add("New Brunswick");
if(province.equals(province)){
return true;
}else{
return false;
}
}
In order to use Arrays, you have to import the library correctly (at the top of the source code, outside the class). Also if you want to compare if the province string is on the list, you could use contains method, like this:
TestA Class
import java.util.ArrayList; // <- import!
public class TestA {
public static void main(String[] args) {
System.out.println(isValidProvince("Alberta"));
System.out.println(isValidProvince("Asd"));
System.out.println(isValidProvince("TEst"));
System.out.println(isValidProvince("British Columbia"));
}
private static boolean isValidProvince(String province) {
ArrayList<String> provinceList;
provinceList = new ArrayList<String>(10);
provinceList.add("British Columbia");
provinceList.add("Alberta");
provinceList.add("Saskatchewan");
provinceList.add("Manitoba");
provinceList.add("Ontario");
provinceList.add("Quebec");
provinceList.add("Newfoundland");
provinceList.add("Prince Edward Island");
provinceList.add("Nova Scotia");
provinceList.add("New Brunswick");
return provinceList.contains(province); //will return true if contains province, false otherwise (this way you avoid if block
}
}
Output:

Java's equals bugging me [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I encountered a problem using equals, let me first add the code here :
Operateur o = new Operateur(nom, age, sexe, grade, role);
for(Operateur op : Membre.getOperateurs()){
if(o.equals((Object)op)){
already_exists = true;
break;
}
}
if(already_exists){
ret = ">Can't create it : already exists";
Membre.removeLast();
o.finalize();
}else{
ret = ">Created it";
}
Here I check if a new Operateur isn't just a copy of an old one (Membre.getOperateurs gets me the list of all instances of Membre that are actual Operateur).
My problem is that when I run this bit of code, if my Operateur is brand new it appears as already existing (which he should not, since he's brand new).
For instance, when I create the first Operateur ever it evaluates it as a duplicate of an already existing one.
As :
import cmd.*;
import matrice.*;
import persona.*;
import non_grata.non.*;
import non_grata.grata.*;
//all above is importing packages to use all classes required
public class Debug{
public static void out(String s){
System.out.println(s);
}//handy
public static void main(String[] args){
Membre.init();//Membre.membre = new ArrayList<Membre>();
Personnel.init();//Personnel.membre = new ArrayList<Membre>();
Vaisseau.init();//Vaisseau.vaisseaux = new ArrayList<Vaisseau>();
MatrixCmd cmd = new MatrixCmd();//Create the command parser
String parser_input = "afficherMembres";//get some input
String parser_output = cmd.execCommand(parser_input);//process it
out(parser_output);//use it
//empty list, correct since we only initialized it
parser_input = "newOPsion mikebike 10 o string string";
parser_output = cmd.execCommand(parser_input);
out(parser_output);
//outputs ">Impossible de créer cet Opérateur : Il existe déjà" which it shouldn't
//since there are no other Operateur and this is only
//given as output when it founds a similar Operateur
parser_input = "afficherMembres";
parser_output = cmd.execCommand(parser_input);
out(parser_output);
//outputs an empty list, meaning that there are no Membre created
//and therefore no Operateur
parser_input = "newOPsion mikebke 8 f tring sring";//command that will trigger the bit of code above
parser_output = cmd.execCommand(parser_input);
out(parser_output);
//outputs">Impossible de créer cet Opérateur : Il existe déjà" which it shouldn't
}
}
Change return super.equals((Object)o) && this.role==o.role;, Object.equals tests reference identity (and you know the Objects are unique instances). Also, don't use == for comparing reference types (like String). I think you wanted
return this.role.equals(o.role);

Error with a Scanner variable in while loop [duplicate]

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.

Categories

Resources