Finding object in ArrayList via user input - Java - java

I'm trying to display Car from fleet ArrayList using user input. Unfortunately I'm not sure how to go about it. I have found few examples online but cannot make them work. I have incorporated following method:
void findRegNo(String reg){
boolean exist=false;
for(int i=0;i<this.fleet.size();i++){
if(this.fleet.get(i).getRegNo() == reg){
exist=true;
break;
}
}
if(exist) {
System.out.println("!!!!!");
} else {
System.out.println("xxx");
}
}
At the moment the result is always: xxx so the code does not find any match. That function is placed in my container class, I was thinking that maybe it supposed to be in different location.
These are variables of Car class:
public class Car {
//defining variables
String regNo;
String model;
double mileage;

Strings are objects, not primitives. Hence, you should use equals to compare their value, not ==, which checks that both references are to the same object:
if (this.fleet.get(i).getRegNo().equals(reg)) {
exist = true;
break;
}

Related

Referencing method from abstract class

START OF INSTRUCTIONS
If there is a game piece on the clicked square (clickedSquare.getPiece()!= null)
Make sure the game piece belongs to the current player. You can get the owning player by calling the getPlayerType() method on the AbstractGamePiece returned by getPiece(). You can then compare that to the currentPlayerTurn JailBreak class member.
If the piece on the clicked square belongs to the current player
Set the selected square equal to the clicked square
Call the select() method on the selected square to show the yellow border
END OF INSTRUCTIONS
I've figured out how to highlight the piece by implementing the select() method, butt
I've tried several different implementations, such as AbstractGamePiece.getPlayerType()==currentPlayerTurn, using nested if statements to set conditions on clickedSquare.getPiece(), and a couple others that I can't think of off the top. I can't seem to get a reference to getPlayerType() from the abstract class. There is pre-written code in the class that seems to work fine as far as accessing the AbstractGamePiece, such as
private void changePlayerTurn()
{
if (currentPlayerTurn == AbstractGamePiece.PLAYER_OUTLAWS)
currentPlayerTurn = AbstractGamePiece.PLAYER_POSSE;
else
currentPlayerTurn = AbstractGamePiece.PLAYER_OUTLAWS;
}
I feel like I'm going about this wrong, but I can't seem to get a reference to the getPlayerType(). The one time I did, I created a new object of the abstract class, but the constructor needs 3 parameters that aren't really appropriate here.
Supporting code:
abstract public class AbstractGamePiece
{
// All class members are provided as part of the activity starter!
// These two constants define the Outlaws and Posse teams
static public final int PLAYER_OUTLAWS = 0;
static public final int PLAYER_POSSE = 1;
// These variables hold the piece's column and row index
protected int myCol;
protected int myRow;
// This variable indicates which team the piece belongs to
protected int myPlayerType;
// These two strings contain the piece's full name and first letter abbreviation
private String myAbbreviation;
private String myName;
// All derived classes will need to implement this method
abstract public boolean hasEscaped();
// The student should complete this constructor by initializing the member
// variables with the provided data.
public AbstractGamePiece(String name, String abbreviation, int playerType)
{
myName = name;
myAbbreviation = abbreviation;
myPlayerType = playerType;
}
public int getPlayerType()
{
return myPlayerType;
}
public void setPosition (int row, int col)
{
myRow = row;
myCol = col;
}
public int getRow()
{
return myRow;
}
public int getCol()
{
return myCol;
}
public String getAbbreviation()
{
return myAbbreviation;
}
public String toString()
{
return (myName + " at " + "(" + myRow + "," + myCol + ")");
}
public boolean canMoveToLocation(List<GameSquare> path)
{
return false;
}
public boolean isCaptured(GameBoard gameBoard)
{
return false;
}
Code that highlights the pieces indiscriminately has been implemented successfully.
private void handleClickedSquare(GameSquare clickedSquare)
{
if (selectedSquare == null)
{
selectedSquare=clickedSquare;
selectedSquare.select();
}
else if (selectedSquare == clickedSquare)
{
selectedSquare.deselect();
selectedSquare = null;
}
else
{
}
Why is it that I'm unable to create a reference to the getPlayerType() method?
Just call getPlayerType on any expression of type X, where X is either AbstractGamePiece or any subclass thereof. For example, square.getPiece().getPlayerType().
Method references are a thing in java and are definitely not what you want, you're using words ('I'm unable to create a reference to getPlayerType') that mean something else. A method reference looks like AbstractGamePiece::getPlayerType, and let you ship the concept of invoking that method around to other code (for example, you could make a method that calls some code 10 times in a row - so this method takes, as argument, 'some code' - and method references are a way to that). It is not what you want here, you want to just invoke that method. Which is done with ref.getPlayerType() where ref is an expression whose type is compatible with AbstractGamePiece. From context, clickedSquare.getPiece() is that expression.

Trouble converting strings of letters to integers

My program asks a question multiple times by an array but I need to get the answer from that String turned into the integer 1. Know I know how to convert any old String into it's integer counterpart if the string is a bunch of number i.e numbers = 12345 using Integer.parseInt(numbers). What happens if I have a character in the string but I want it to take an integer value of 1? I've got it set out this like this so far
String[] elements = {"Vote A for Football", "Vote B for Basketball"};
String question
int football = 0; // not sure if these should be strings or integers
int basketball = 0;
int tally;
for (String element : elements)
{
System.out.println(element);
}
question = JOptionPane.showInputDialog("What is your favourite sport?");
tally = Integer.parseInt(question);
The last line is the part that gets me because I want them to vote by either entering A or B but I also need the console to print how many times they have voted for that sport (it's an array exercise so the question will appear multiple times).
Welcome to SO. I'm not sure what you're asking, but it would be best to keep the storage of values as integers, and keep strings more of an interface to the user. This way you can readily calculate values without any conversion. Only when you present it to the user should you need to convert.
Having said that, if you are parsing a string (like "A" or "B"), you can store their response as a string, and then compare it against a list of known values using if and equals:
if ("A".equals(question)){
football++;
} else if ("B".equals(question)) {
basketball++;
} else {
// do nothing, process error, ask question again.
}
Also remember to close your statement when initializing your variable:
String question;
or
String question = "";
But as #Jean-François Savard mentions, the variable should make sense as well, so this would be clearer:
String userResponse = "";
Another approach to use Enums
public enum Game {
A {
#Override
public String getGame() {
return "Football";
}
#Override
public int getNumber() {
// TODO Auto-generated method stub
return 1;
}
},
B {
#Override
public String getGame() {
return "Basketball";
}
#Override
public int getNumber() {
// TODO Auto-generated method stub
return 2;
}
};
public abstract String getGame();
public abstract int getNumber();
}

Manipulating Variables using Setters and Getters

I came across this code example on another website. I've been looking at it for a while, trying to figure out something simple, but I'm having difficulty determining where to start.
How would I allow a user to enter into the console to turn the light or the fan on/off?
All this stuff with setters/getters is confusing. Writing the logic of turning something on/off seems simple, but mix it in with constructors and setters/getters and I get lost. I'm failing to understand how and where to manipulate the isOn boolean with user input.
I'd appreciate any guidance or code.
Thanks
public class Household {
public String choice;//instance variables
public boolean isOn;
//constructor
Household(String choice,boolean isOn) {
this.isOn=isOn;
this.choice=choice;
}
//methods
public String getChoice() {
return choice;
}
public void setChoice(String choice) {
this.choice = choice;
}
public boolean isOn() {
return isOn;
}
public void setOn(boolean isOn) {
this.isOn = isOn;
}
public String toString() {
return "Choice:" + getChoice() + "\tisOn:" + (isOn() ? "Yes" : "NO");
}
public static void main(String[] args) {
Household hh=new Household("toaster", true);
System.out.println(hh);
hh=new Household("fan", false);
System.out.println(hh);
}
}
You can think of a constructor as like a blueprint.
In the above picture, we have the class in the dotted box. This is the "blueprint." It's not an actual object yet, it just represents how objects should look. In the solid box is an actual object.
The constructor takes the blueprint and actually builds something from it.
Household(String choice,boolean isOn) {
this.isOn=isOn;
this.choice=choice;
}
Here, we're defining how that blueprint works. In order to build a household object, we need to supply it with a string "choice" and a boolean "isOn".
Once we have those two things, we can create a Household object.
Now, you can't turn on the lights in your house before they're built.
Once you have a Household object, you'll also have your choice and isOn fields.
Say I want to turn off whatever is in the house.
Using your code, we have a household named hh, a toaster, and an on/off switch. If you wanted to turn off the on/off switch, you'd use the setter:
public void setOn(boolean isOn) {
this.isOn = isOn;
}
The setter then sets the value of the isOn field on the hh object, as seen in the above picture.
If you wanted to know whether that switch was true or false (on or off), you'd ask:
hh.getOn();
This returns a boolean value, the same value as the isOn field on the object.
You can see this when you call
System.out.println(hh.getOn());
This prints out true or false, depending on whether or not it's set to true or false.
That's how setters and getters work: the setter sets the value of that field, and the getter gets the value of the field.
Now for the (more) fun part.
Since you want to input data, rather than simply outputting data, we have to do something different.
Say I want to have a user type into the console "off" and have it set the households on/off switch to off.
System.out.println(hh); <-- only prints out to console
We need a new object to handle input. Scanner is commonly used for teaching beginners, so we'll use that.
Scanner s = new Scanner(System.in);
This reads data from the system's input stream. You can read about Scanner here.
Now, scanner reads data in as a string using nextLine();
So we'll use that.
String test = s.nextLine();
And of course now we need to test if that string is the same as "off", and if it is, set the isOn field to false (off).
if(test.equals("off") || test.equals("OFF")){
hh.setOn(false);
}
I won't go into more details on how to do the rest of this, such as checking input, looping, etc.
The logic should be in the main method in this application.
Wherever you need to modify the household object is where you need to call those setter/getter methods. The constructor is only ever called when you need a brand new object. If this is still confusing, compare the constructor to setting up a game of monopoly. You initially set up the monopoly board, give everyone their money and starting properties, etc. This is all done so that you can actually play the game. When you lose a property in the game, you would use a setter to remove that property. When you need to see how much money, you'd use a getter.
MonopolyPlayer{
int cash;
MonopolyPlayer(){
cash = 1500;
//we're setting this player up to play the game
}
setCash(int i); //now the player has a new amount of cash
getCash(); // he's checking his account
....etc.
}
And so on.
So to try and break it down.
The idea behind getters and setters is to be able to retrieve and set data on variables inside an object, without having to expose the variables themselves. This means that the fields you have at the top of your class should be declared private. You only want to be able to access them through getters and setters.
In your main method you create an instance of the Household object by using the constructor (you can think of the constructor as the thing which constructs the instance). Your constructor says that to call it, it needs two pieces of data, a String and a boolean. When the constructor is called with these two pieces of data it then stores them in the instance it creates in the fields choice and isOn.
Now that you have your instance of Household (hh), you have an object which contains two pieces of data. If you want to retrieve the data you have stored for one of the variables, you use the getter.
hh.getChoice();
or
hh.isOn();
This will return you the data stored in the choice/isOn field for that specific instance of Household.
If you want to change the data you have stored in hh, you use the setters. So to change the value if isOn you would use
hh.setOn(true);
or
hh.setOn(false);
How would I allow a user to enter into the console to turn the light or the fan on/off?
Using your code, you could do something like this.
public static void main(String[] args) {
System.out.println("Enter On or Off for fan: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
boolean on = false;
if(input.equalsIgnoreCase("yes")) {
on = true;
} else if( input.equalsIgnoreCase("no")) {
on = false;
} else {
System.out.println("Please enter yes or no!");
return;
}
Household fan=new Household("fan", on);
System.out.println(hh);
}
But this isn't really using your setters or getters. You could create your household class like this,
public class Household {
private String choice;//instance variables
private boolean isOn;
public void setOn(boolean isOn) {
this.isOn = isOn;
}
public boolean getOn() {
return isOn;
}
public void setChoice(String choice) {
this.choice = choice;
}
public String getChoice() {
return choice;
}
public String toString() {
return "Choice:" + getChoice() + "\tisOn:" + (isOn() ? "Yes" : "NO");
}
}
And in my code above switch it to:
Household fan = new Household();
fan.setChoice("fan");
fan.setOn(on);
System.out.println(fan);

Comparing objects never returns true

I'm trying to compare two objects of the same type (in method doesHave), but I've never got "true" returned. Here's my code:
private ArrayList<Osoba> osoba = new ArrayList<Osoba>();
public boolean doesHave(Osoba o) {
for (int i = 0; i < osoba.size(); i++) {
if (pobierz(i).equals(o))
return true;
}
return false;
}
public Osoba pobierz(int index) {
return osoba.get(index);
}
The 'Osoba' class, looks like this:
public class Osoba {
private String imie;
private String nazwisko;
public String toString() {
return imie + " " + nazwisko;
}
public Osoba(String name, String surname) {
imie = name;
nazwisko = surname;
}
public String getImie() {
return imie;
}
public String getNazwisko() {
return nazwisko;
}
}
Code from main:
Osoba osoby = new Osoba(name, surname);
if (kartoteka.doesHave(osoby) == Boolean.TRUE) {
temp = odczyt.nextLine();
if (temp.equals("y"))
kartoteka.usun(osoby); //some method
else
...
}
No matter what input I'd use, this part never happens.
'kartoteka' is my package which of course I have imported. Each class is in separate package, but there is no problem with using them. I've tried googling it for quite some time, but nothing helped me, it just seems like
if (kartoteka.doesHave(osoby) == Boolean.TRUE)
Is never true, but I have no idea why. Code without Boolean.TRUE doesn't work as well. If I could get some hints, I'd be thankful. Sorry for asking that kind of question, but I'm new in java.
Imagine that you and your wife have twins.
Are they the "same" person? No, they are not. Lets call them twin A and twin B. They are two different instances, yes, they look same, but if you are talking twin A, you are not talking about twin B and vice versa. The point is, they are not EQUAL :), it is same in Java. Twin A is equal only to itself, no1 else.
You have to create your own method, which compares all properties of two instances of Osoba.
The other option is to override the equals and hashCode methods, but it is not good approach in your case.
Right now your code checks if the memory address of two objects is the same which can only be true if it is the same exact object.
You need to implement a method that compares two Osoba objects by comparing whichever properties you want from these objects and returning true/false appropriately.
Osaba should implement equals:
#Override
public boolean equals(Object other) {
return imie.equals(((Osaba) other).getImie())
&& nazwisko.equals(((Osaba) other).getNazwisko()));
}
If you do not implement equals, the default implementation will be used.
Responds from #libik and #Code Whisperer helped me, so if anyone has the same problem, read and try to understand, it helped for me. I like that twins allegory :) It's kind of the same situation when I tried to compare two Strings.

Java see if arraylist contains string

I have a class called Paragens like this:
public class Paragens {
static int contadorParagens = 1;
String nomeParagem;
int id;
public Paragens(String nomeParagem) {
this.nomeParagem = nomeParagem;
this.id = contadorParagens++;
}
// getters and setters for nomeParagem
}
Every Paragens object has a name and an Id.
This class has a main method where I create several Paragens objects and store them inside an ArrayList like this:
public static void main(String[] args) {
ArrayList<Paragens> paragens = new ArrayList<Paragens>();
paragens.add(new Paragens("name1");
// ... add more paragens
}
This is working ok. If I insert a bunch of paragens and print them I can see tat is all ok.
What I am trying to do is to ask the user to input a paragem name and then I want to see if that paragem is already in the ArrayList.
String name;
System.out.println("Insert paragem name: ");
pickName = sc.nextLine();
System.out.println(paragens.contains(pickName));
What am I doing wrong?
contains checks to see if the list contains the actual thing you handed it. In this case, you're passing in a String name, but comparing it to Paragem instances. contains can't magically guess that it's supposed to look at a given property on the Paragem instances to compare the string.
You can easily loop the list to find out for yourself:
boolean found = false;
for (Paragem p : paragems) {
if (p.nomeParagem.equals(pickName)) { // Or use an accessor function for `nomeParagem` if appropriate
found = true;
break;
}
}
...or as a function:
boolean containsParagemWithName(ArrayList<Paragem> paragems, String pickName) {
for (Paragem p : paragems) {
if (p.nomeParagem.equals(pickName)) {
return true;
}
}
return false;
}
Well, you need to implement the contains method yourself. Do a for loop over the entire array and check if the name of one of the elements is equal with what you're trying to add. If not, add a new Paragens(pickName).
Objects by default are compared by their memory location. So if you have two Paragem with the same name, they are still not equal.
So either, you check the name of each one:
boolean checkDuplicate(String pickName) {
for (Paragem p : paragems) {
if (p.nomeParagem.equals(pickName)) return true;
}
return false;
}
or implement (override) the equals method to compare names (you should be calling contains on a new Paragem object then instead of a String, though).

Categories