make a global object in java - java

I want to make an array of objects and use it in different functions. I wrote this pseudocode
privat stock[] d;
privat stock example;
public void StockCheck(){
d =new stock[2];
d[0]= new stock("a","test1", 22);
d[1]= new stock("b","test2", 34);
}
#Override
public stock getStock(String name) throws StockCheckNotFoundException{
int i;
System.out.println("ok" + name + d.legth); // error
example = new stock("example","example",2);
return example;
}
In class test I make an instance of getStock and I call the function getStock stock.getStock();
I get a NullPointerExeption when I do d.length. d is null but I don't understand why.

Hmmmm. If that is in any way like your real code, then the problem is that your "constructor" isn't really a constructor, as you've declared it to return void, making it an ordinary method instead. Remove tbat "void" and it may fix the problem!

Perhaps this example of code will do what you need, using three classes
Test - the main test code
Stock - the implied code for Stock from your question
StockCheck - the corrected code from your question.
(Note: you may really want to use an ArrayList inside StockQuote so you can add and delete Stocks.)
Test class
package stackJavaExample;
public class Test {
public static void main(String[] args) {
String[] testNames = {"test1","test2","notThere"};
StockCheck mStockCheck = new StockCheck();
for (int i=0; i<testNames.length; i++) {
Stock result = mStockCheck.getStock(testNames[i]);
if (result == null) {
System.out.println("No stock for name: " + testNames[i]);
} else {
System.out.println("Found stock: " + result.getName() + ", " + result.getSymbol() + ", " + result.getValue());
}
}
}
}
Stock class
package stackJavaExample;
public class Stock {
private String symbol;
private String name;
private double value;
public Stock(String symbol, String name, double value) {
this.symbol = symbol;
this.name = name;
this.value = value;
}
public String getSymbol() { return symbol;}
public String getName() { return name;}
public double getValue() {return value;}
}
StockCheck class
package stackJavaExample;
public class StockCheck {
private Stock[] d;
public StockCheck() {
d = new Stock[2];
d[0] = new Stock("a","test1", 22);
d[1] = new Stock("b","test2", 34);
}
public Stock getStock(String name) {
for (int i=0; i < d.length; i++) {
if (d[i].getName().equalsIgnoreCase(name)) {
return d[i];
}
}
return null;
}
}

Related

How can I use the indexOf() function to find an object with a certain property

I have an object, Pet, and one of the functions is to retrieve its name.
public class pet{
private String petName;
private int petAge;
public pet(String name, int age){
petName = name;
petAge = age;
}
public String getName(){
return petName;
}
public int getAge(){
return petAge;
}
}
I then have an ArrayList which holds a collection of pets as shown in the code below:
import java.util.ArrayList;
pet Dog = new pet("Orio", 2);
pet Cat = new pet("Kathy", 4);
pet Lion = new pet("Usumba", 6);
ArrayList<pet> pets = new ArrayList<>();
pets.add(Dog);
pets.add(Cat);
pets.add(Lion;
I was wondering how I could retrieve the index in the ArrayList or the object that has the name I need. So if I wanted to find out how old Usumba was, how would I do this?
Note: This is not my actual piece of code, it's just used so that I can better explain my problem.
Edit 1
So far, I have the following but I was wondering if there was a better or more efficient way
public int getPetAge(String petName){
int petAge= 0;
for (pet currentPet : pets) {
if (currentPet.getName() == petName){
petAge = currentPet.getAge();
break;
}
}
return petAge;
}
You can't use indexOf() for this purpose, unless you abuse the purpose of the equals() method.
Use a for loop over an int variable that iterates from 0 to the length of the List.
Inside the loop, compare the name if the ith element, and if it's equal to you search term, you've found it.
Something like this:
int index = -1;
for (int i = 0; i < pets.length; i++) {
if (pets.get(i).getName().equals(searchName)) {
index = i;
break;
}
}
// index now holds the found index, or -1 if not found
If you just want to find the object, you don't need the index:
pet found = null;
for (pet p : pets) {
if (p.getName().equals(searchName)) {
found = p;
break;
}
}
// found is now something or null if not found
As the others already stated, you cannot use indexOf() for this directly. It would be possible in certain situations (lambdas, rewriting hashCode/equals etc), but that is usually a bad idea because it would abuse another concept.
Here's a few examples of how we can do that in modern Java:
(as the index topic has already been answered quite well, this only handles direct Object return)
package stackoverflow.filterstuff;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
public class FilterStuff {
public static void main(final String[] args) {
final Pet dog = new Pet("Orio", 2); // again, naming conventions: variable names start with lowercase letters
final Pet cat = new Pet("Kathy", 4);
final Pet lion = new Pet("Usumba", 6);
final ArrayList<Pet> pets = new ArrayList<>();
pets.add(dog);
pets.add(cat);
pets.add(lion);
try {
simpleOldLoop(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
simpleLoopWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreams(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreamsWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
}
private static void simpleOldLoop(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleOldLoop()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleOldLoop(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_simpleOldLoop(pPets, "Hans"));
}
private static Pet filterPet_simpleOldLoop(final ArrayList<Pet> pPets, final String pName) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
if (Objects.equals(pet.getName(), pName)) return pet;
}
return null;
}
private static void simpleLoopWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleLoopWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Kathy"))));
System.out.println("Pet named 'Hans': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Hans"))));
}
private static Pet filterPet_simpleLoopWithLambda(final ArrayList<Pet> pPets, final Function<Pet, Boolean> pLambda) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
final Boolean result = pLambda.apply(pet);
if (result == Boolean.TRUE) return pet;
}
return null;
}
private static void filterStreams(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreams()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, "Hans"));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final String pName) {
return pPets.stream().filter(p -> Objects.equals(p.getName(), pName)).findAny().get();
}
private static void filterStreamsWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreamsWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, p -> Objects.equals(p.getName(), "Kathy")));
final Predicate<Pet> pdctHans = p -> Objects.equals(p.getName(), "Hans"); // we can also have 'lambda expressions' stored in variables
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, pdctHans));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final Predicate<Pet> pLambdaPredicate) {
return pPets.stream().filter(pLambdaPredicate).findAny().get();
}
}
Along with your Pet class, extended by toString():
package stackoverflow.filterstuff;
public class Pet { // please stick to naming conventions: classes start with uppercase letters!
private final String petName;
private final int petAge;
public Pet(final String name, final int age) {
petName = name;
petAge = age;
}
public String getName() {
return petName;
}
public int getAge() {
return petAge;
}
#Override public String toString() {
return "Pet [Name=" + petName + ", Age=" + petAge + "]";
}
}

Java testing out a driver class

I've been having some issues with this program. I have to test out using a driver class each method, but I can't seem to understand what I should do when the parameters are strings.
I had an example for int parameters but the example never showed anything on string parameters and how to convert. Using null makes my driver class run but putting an int or string won't.
What can I do to convert this correctly, so it can display whatever I have in the no parameter constructor?
public class StudentListing
{
private String name;
private String number;
public StudentListing(String n, String num)
{
name = n;
number = num;
}
public StudentListing()
{
name = null;
number = null;
}
public String toString()
{
return("Name is " + name +
"\nNumber is " + number + "\n");
}
public void show()
{
System.out.println(toString());
}
public StudentListing Clone()
{
StudentListing clone = new StudentListing (name, number);
return clone;
}
public int compareTo(String targetKey)
{
return (name.compareTo(targetKey));
}
public void input()
{
name = JOptionPane.showInputDialog("Enter a name");
number = JOptionPane.showInputDialog("Enter a number");
}// end of StudentListing
}//end of class
public class StudentListingDriver
{
public static void main(String[] args)
{
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null,null);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.clone();
s1.show();
}
}
You can have default values and make the no-args constructor call the other constructor.
Use Integer.parseInt(); to convert from a String to an Integer.
You also need to check the conversion for exceptions.
Like this:
public class StudentListing {
private String name;
private int number;
public StudentListing(String n, int num) {
name = n;
number = num;
}
public StudentListing() {
this("defaultName", 0);
}
public String toString() {
return ("Name is " + name + "\nNumber is " + number + "\n");
}
public void show() {
System.out.println(toString());
}
public StudentListing Clone() {
StudentListing clone = new StudentListing(name, number);
return clone;
}
public int compareTo(String targetKey) {
return (name.compareTo(targetKey));
}
public void input() {
name = JOptionPane.showInputDialog("Enter a name");
number = Integer
.parseInt(JOptionPane.showInputDialog("Enter a number"));
}
}
The tester:
public class StudentListingDriver {
public static void main(String[] args) {
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null, 0);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.Clone();
s1.show();
}
}

What is the correct way to do this?

I know this must be a fundamental design problem because I clearly can't do this. I want to call the ownGrokk, ownTyce, etc methods from another class depending on the value of the integer assigned to OwnedSpirits(int). This in turn fills arrays.
The problem is, I do this multiple times, and doing it from another class it seems like I have to make a new object every time to pass the new int argument, and doing so resets the value of spiritInstance. And, since that resets to zero, the arrays don't fill properly. I try to print out my array values later and I get an "ArrayIndexOutOfBoundsException".
public class OwnedSpirits {
private int spiritTypeInt = 0;
public static int spiritInstance=0;
public static int[] spiritarray = new int[9];
public static String[] spiritName = new String[9];
public static int[] party = new int[3];
public OwnedSpirits(int spiritcall){
if(spiritcall == 1){
ownGrokk();
}
if(spiritcall == 2){
ownRisp();
}
if(spiritcall == 3){
ownTyce();
}
if(spiritcall == 4){
ownDaem();
}
if(spiritcall == 5){
ownCeleste();
}
}
private void ownGrokk(){
spiritName[spiritInstance] = "Grokk";
spiritInstance++;
}
private void ownRisp(){
spiritName[spiritInstance] = "Risp";
spiritInstance++;
}
private void ownDaem(){
spiritName[spiritInstance] = "Daem";
spiritInstance++;
}
private void ownCeleste(){
spiritName[spiritInstance] = "Celeste";
spiritInstance++;
}
private void ownTyce(){
spiritName[spiritInstance] = "Tyce";
spiritInstance++;
}
and this code is in another class, where it attempts to call the methods to fill the array
buttonConfirm.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
if(xcounter==3){
for(x=0; x<3; x++){
if(setdaemtrue == true){
new OwnedSpirits(4);
}
if(setrisptrue == true){
new OwnedSpirits(2);
}
if(setcelestetrue == true){
new OwnedSpirits(5);
}
if(settycetrue == true){
new OwnedSpirits(3);
}
if(setgrokktrue == true){
new OwnedSpirits(1);
}
}
}
}
});
and finally in yet another class:
System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);
#Override
public void show() {
System.out.println(partylist[0]);
System.out.println(partylist[1]);
System.out.println(partylist[2]);
spiritlist.setItems(partylist);
table.add(spiritlist);
table.setFillParent(true);
stage.addActor(table);
}
If the last part is confusing, it's because I am using libgdx. the print statements are there just to try to figure out why my list was having an error
I can show you what I would do to handle Spirits, and Parties.
The Spirit class, contains name and current party its assigned to:
package com.stackoverflow.spirit;
public class Spirit {
private String name;
private Party party;
private SpiritType type;
private static int id = 0;
public static enum SpiritType {
Grokk, Risp, Tyce, Daem, Celeste
};
public Spirit(String name, SpiritType type) {
create(name, type);
}
public Spirit(SpiritType type) {
create(null, type);
}
// This is to handle Java inexistance of default parameter values.
private void create(String name, SpiritType type)
{
Spirit.id++;
this.name = (name == null) ? (type.name() + " " + id) : name;
this.type = type;
}
public String getName() {
return name;
}
public Party getParty() {
return party;
}
public SpiritType getType() {
return type;
}
/**
* Used internally by #see Party
* #param party the party this Spirit belongs
*/
public void setParty(Party party) {
this.party = party;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString()
{
return this.name;
}
}
Finally the Party class, contains a set of Spirits, you can add and remove Spirits from the party.
package com.stackoverflow.spirit;
import java.util.HashSet;
public class Party {
private HashSet<Spirit> spirits = new HashSet<Spirit>();
private static int id = 0;
private String name = "Party " + Party.id++;;
public Party() {
}
public Party(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(Spirit spirit) {
if (!spirits.contains(spirit)) {
spirits.add(spirit);
if (spirit.getParty() != null) {
//Remove from previous party to update the other party set
spirit.getParty().remove(spirit);
}
spirit.setParty(this);
} else {
// throw new SpiritAlreadyOnParty();
}
}
public void remove(Spirit spirit)
{
if (spirits.contains(spirit))
{
spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
spirits.remove(spirit);
}
else {
//throw new SpiritNotInParty();
}
}
public boolean isOnParty(Spirit spirit) {
return spirits.contains(spirit);
}
public ArrayList<Spirit> getSpirits()
{
return new ArrayList<Spirit>(spirits);
}
public int getPartySize() {
return spirits.size();
}
public String getPartyInfo()
{
StringBuilder builder = new StringBuilder();
builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
for (Spirit s : spirits)
{
builder.append(s.getName() + "\n");
}
return builder.toString();
}
#Override
public String toString()
{
return this.name;
}
}
Here I use the Spirit and Party classes, you could add more functionality, like properties for party strength, magic buffs on the party, etc:
package com.stackoverflow.spirit;
import com.stackoverflow.spirit.Spirit.SpiritType;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Party griffindor = new Party("Griffindor"), slytherin = new Party(
"Slytherin");
// You can also do for (SpiritType type : SpiritType.values() then
// type.ordinal()
for (int i = 0; i < SpiritType.values().length; i++) {
griffindor.add(new Spirit(SpiritType.values()[i]));
slytherin.add(new Spirit(SpiritType.values()[i]));
}
Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);
slytherin.add(mySpirit);
System.out.println("Name of party:" + mySpirit.getParty().getName());
System.out.println("Is on griffindor?:"
+ griffindor.isOnParty(mySpirit));
// What now?
griffindor.add(mySpirit);
System.out.println("Is " + mySpirit.getName() + " on "
+ slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));
System.out.println(mySpirit.getName() + " is now on "
+ mySpirit.getParty() + "\n");
System.out.println(griffindor.getPartyInfo());
System.out.println(slytherin.getPartyInfo());
}
}
P.D: I'm not a HP fan.

The type of the expression must be an array type but it resolved to

Im new to java. I dont understand why these errors are occurring. trying to make an array list so that it saves each object. The errors im getting are The type of the expression must be an array type but it resolved to ArrayList on the line 'newbug1[i].setspecies();'
Thankyou in advance
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Abug2 {
private String species;
private String name;
private char symbol = '\0';
private int horposition = 0, verposition = 0, energy = 0, uniqueID = 1, counter;
public Abug2(String species, String name, char symbol)
{
uniqueID = counter;
counter++;
}
public void setspecies(){
species = JOptionPane.showInputDialog(null, "Enter the species: ");
}
public String getspecies(){
return species;
}
public void setname(){
name = JOptionPane.showInputDialog(null, "Enter the name: ");
}
public String getname(){
return name;
}
public void setsymbol(){
symbol = name.charAt(0);
}
public char getsymbol(){
return symbol;
}
public int getid(){
return uniqueID;
}
public int gethorizontal(){
return horposition;
}
public int getvertical(){
return verposition;
}
public int getenergy(){
return energy;
}
//The class ABug has a set of methods: two or more constructors, toString, toText, and getters and setters for the attributes
public String toString(){
String tostring = "\nName: " + name + "\nHorizontal Position: " + horposition + "\nVertical Position: " + verposition + "\n";
return tostring;
}
public String toText(){
String totext = getspecies() + getname() + getsymbol() + getid() + gethorizontal() + getvertical() + getenergy();
return totext;
}
public static void main (String [] args){
ArrayList<Abug2> newbug1 = new ArrayList<Abug2>();
String choice = JOptionPane.showInputDialog(null, "Would you like to add another bug?: ");
do{for (int i = 0; i < 3; i++) {
newbug1.add(new Abug2("Bug", "Spider", 's'));
newbug1[i].setspecies();
newbug1[i].setname();
newbug1[i].setsymbol();
System.out.println(newbug1[i].toString());
} }while(choice != "yes");
}
}
For arraylists use get() instead:
newbug1.get(i).setspecies();
newbug1.get(i).setname();
newbug1.get(i).setsymbol();
Because it stores object references any setFoo calls affect the original object referenced in the arraylist.
In order to access an element in an ArrayList you have to use a method called get.
In your code, replace newbug1[i] by newbug1.get(i)
And moreover, you should store that reference in a variable instead of recalling it again and again:
Abug2 currentBug = newbug1.get(i);
currentBug.setSpecies();
Your code will gain in clarity.

How to in a class, use an attribute of a different class to find out the other attribute. (java)

Sorry if i'm being vague here, i'll post my code for you guys too. I'm a beginner so go easy on me.
I have a class called student, it has an int id, and another String name. I have created another Class for the GUI. It has a window that pops up and has a field for the id. I want to enter the ID and get the Name from that ID. I have no idea of going about this and i've been stuck for hours. I'm kind of slow to catch on, so could someone help me? I'm not very good at inheritance. (also, i have two other classes, but i don't think they would be of any help here.
STUDENT CLASS
public class Student {
private int id;
private String name;
private ArrayList<Course> regCourses;
public int getId() {
return id;
}
public String getName() {
return name;
}
public ArrayList<Course> getRegCourses() {
return regCourses;
}
public Student(int i, String n) {
id = i;
name = n;
regCourses = new ArrayList<Course>();
}
public String toString() {
String answer = id + " " + name + " - Registered Courses: ";
if (regCourses.size() == 0)
answer += "NONE";
else {
for (int i = 0; i < regCourses.size(); i++) {
answer += regCourses.get(i).getDepartment().getId()
+ regCourses.get(i).getCode();
if (i != regCourses.size() - 1)
answer += ", ";
}
}
return answer;
}
public void registerFor(Course c) {
if (!isRegisteredInCourse(c)) {
// Register
regCourses.add(c);
if (!c.getClassList().contains(this)) {
c.getClassList().add(this);
if (!c.getDepartment().getStudentList().contains(this))
c.getDepartment().getStudentList().add(this);
}
}
}
public boolean isRegisteredInCourse(Course c) {
return regCourses.contains(c);
}
}
And here's the search code in another class.
public class MainGUIWindow extends JFrame implements ActionListener {
JLabel studentID, studentName, currentRegCourses;
JButton search, regForCourse, withdraw;
JTextField idField, nameField;
JScrollPane courseScrollList;
public MainGUIWindow(String title) {
super(title);
//GUI STUFF
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == search) {
if (idField.getText() != null) {
int id = Integer.parseInt(idField.getText());
Student temp = null;
//CODE GOES HERE
}
}
}
public static void main(String[] args) {
new MainGUIWindow("Student Administration System").setVisible(true);
Also, if need be, these all my java files.
http://www.filehosting.org/file/details/426633/JavaCode-SO.zip
Edit: There are 2 more Classes that are my test programs that have data in them.
You could store the Students in a Hashmap or treemap and then look them up
i.e
HashMap<Integer,Student> studentMap = new HashMap<>();
studentMap.put(matt.getId(), matt);
.....
Student s = studentMap.get(lookupId); /* Retrieve based on Student id*/

Categories

Resources