Java's equals bugging me [duplicate] - java

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);

Related

cant print the arrays [duplicate]

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.

Instantiating a Java Object to the passed Object Reference [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
this is the test code I am using to understand how java handles object memory.
public class TestCode {
public static void main(String[] args) {
TestCode obj = new TestCode();
CustomClass cs1 = new CustomClass(5);
obj.updateExistingObj(cs1);
System.out.println(cs1.val);
CustomClass cs2 = new CustomClass(5);
obj.instantiateExistingObj(cs2);
System.out.println(cs2.val);
CustomClass cs3 = null;
obj.updateNullObj(cs3);
System.out.println(cs3.val);
}
void updateExistingObj(CustomClass cs1) {
cs1.val = 9;
}
void instantiateExistingObj(CustomClass cs2) {
cs2 = new CustomClass(9);
}
void updateNullObj(CustomClass cs3) {
cs3 = new CustomClass(9);
}
}
class CustomClass {
int val;
CustomClass next;
CustomClass(int x) { val = x; }
}
The output of the first syso where I am printing cs1.val I am getting expected value which is 9.
The output of the second syso where I am printing cs2.val I am getting 5 as output instead of 9.
The output of the third syso where I am printing cs3.val I am getting a null pointer exception.
Can anybody help me understand what is happening here under the hood? How exactly java handles the memory location when we pass an object as a function parameter? Thanks for helping!!
cs2 and cs3 are local variable, assigning a new value to them have no effect outside of the methods where they are declared.

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:

Referencing between class Object initialized with null [duplicate]

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?

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