java: using an array of objects across files - java

OK so, im very new to java and the solution is probably simple so please bear with me, but basically i'm trying to make a film database using an array of a movie class. i have 3 .java files: the tester, the database, and the movie class. my problem is i'm really not sure how to make my tester file recognize the movies array from the database file, and every solution ive found has just given me more errors.
tester:
public class DatabaseTester extends MovieDatabase{
public static void main(String[] args) {
System.out.println(MovieDatabase.movies[1].getTitle());
}
}
the database:
public class MovieDatabase {
public static Movie movies[] = new Movie[2];
public static void movieDb(String[]args){
movies[1].setTitle("Test Title");
}
}
^the movie class has a set title method. i'm not too sure about the database's code in particular but it was the only way i could find that didn't give me errors. i'll post the full movie class if necessary but it's quite long so... only if needed
the error i get if i try to getTitle(); from the MovieDatabase:
Exception in thread "main" java.lang.NullPointerException
at DatabaseTester.main(DatabaseTester.java:35)
i'm aware this error is from the program thinking the array is not initialized, so it just must not be recognizing my database file... if i try to getTitle from the MovieDatabase, it simply doesn't recognize it, and will either give me an error or nothing. i cannot find a way to get around this aside from putting the Movie initialization in the main (which i have confirmed works, but it's not what i want to do).

You can try this the following changed code In the class DatabaseTester
public class DatabaseTester {
public static void main(String[] args) {
System.out.println(Database.movies[0].getTitle());
}
}

Related

Instantiating Objects in Java

I asked a similar question to this recently, but I did a bad job at explaining it, so I am going to try again.
I cannot figure this out for the life of me. I have to do two different java files for this programming assignment, and when running the program from command prompt I get an error that says it cannot find symbol of when I create my object in the second class, and when I run the code in Eclipse I get the error "Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package jdk.internal.jrtfs in both module jrt.fs and module java.base".
I even copied an example straight from the textbook to understand it, but it isn't working even though I have exactly what's in the textbook. The pastebin links are for the two classes that come from the textbook examples.
Please someone tell me what's wrong here.
First class: https://pastebin.com/KYHtDHPt
public class Account {
private String name;
public Account(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Second class: https://pastebin.com/ADUsjjaR
public class AccountTest {
public static void main(String[] args) {
Account account1 = new Account("Brandon Williams");
System.out.printf("Account one is: %s%n",account1.getName());
}
}

Java ArrayList a good way to access same list from many classes

Hello i am trying to familiarize myself with Java by doing a very simple "bankaccount" application and it doesn't even save to db or something so it resets all data on rerun.
The problem i am trying to find a good way of doing is that i have an ArrayList of accounts that i want to be able to access from any class so that during runtime for example after an deposit if i access that account later when i want to get balance i get an that account from the ArrayList and it is updated to the deposit value.
When googling i found this solution but i dont like it since it uses static ArrayList. is there any more elegant way than this for an applicaiton that only saves the state/data during runtime.
Simple class that adds the test accounts and so on where first value is acountId and second is balance
public class AccountsModel {
private ArrayList<AccountModel> listOfAccounts;
public AccountsModel() {
listOfAccounts = new ArrayList<AccountModel>();
listOfAccounts.add(new AccountModel(1,0));
listOfAccounts.add(new AccountModel(2,0));
listOfAccounts.add(new AccountModel(3,0));
listOfAccounts.add(new AccountModel(4,0));
}
public ArrayList<AccountModel> getListOfAccounts(){
return listOfAccounts;
}
}
Then in my main class i just do this
static AccountsModel accounts = new AccountsModel();
public static ArrayList<AccountModel> listOfAccounts = accounts.getListOfAccounts();
this "works" as i can get the same list from anywhere within the application. But is there any simple and elegant way of doing this some other way?
You said you dislike the static solution but to me "It needs to be accessed by many classes" screams static variables.
Basically, you create a wrapper for your ArrayList which carries out operations:
class AccountsModel {
private static ArrayList<AccountModel> singleton;
// a static constructor also wouldn't be a bad idea here
public static void init() {
/* add a bunch of AccountModels here*/
}
public static ArrayList<AccountModel> getAccounts() {
return singleton;
}
}
An example of a main method:
public static void main(String[] args) {
ArrayList<AccountModel> accounts = AccountModels.getAccounts();
}

What is the (best)name or description of this "method linking" to other components

First off, sorry for the strange "title", but since I don't know the name, it's quite tough to describe in a short sentence.
I've been here many-many times before, however this is my first actual activity.
I usually search, read and fight my way trough what I want to know. However, I just can't seem to get to my answer this time, which I find pitty.
Lately I've read "Head First Design Patterns", which I can't recall it was covered in there. Also I've hit quite some Google terms in the box, but without the correct defenition. I just can't find the right combination of search-words to nail the answer.
I've got a question about the correct name of "forward sharing / linking"
of methods and their parameters.
I'm writing the JavaDocs comments to keep my code understandable, but I can't get the right term or Design Pattern name that fits to this.
But just asking this won't get me what I need i think. So I've got a little sample to demonstrate my question as BASIC as possible. I hope it is a bit understandable.
public class Framework()
{
private Game game = new Game();
public Framework()
{
loadComponents();
}
public void loadComponents()
{
// first loading framework requirements.. (lets say a button graphic)
game.load(); // lets start loading the game....
}
public static void main (String[] args)
{
new Framework();
}
}
public class Game()
{
private World world = new World();
public void load()
{
// now we load some of the basic graphics.. (lets say a few borders)
world.load(); // lets start loading the world!
}
}
public class World()
{
private Textures textures = new Textures();
public void load()
{
// now we load the worlds grid...
textures.load(); // ofcourse we need textures, lets load...
}
}
public class Textures()
{
public void load()
{
// loading the textures...
// end of this loading link.
}
}
In this example we started off in the Framework, called the load method in Game, then called the load method in World,
then called the load method in Textures. Lets make it a little simpler:
Framework.load()->Game.load()->World.load()->Texture.load();
But ofcourse we got more of these "links".
Framework.load()->Editor.load()->Entities.load();
Framework.input(Input input)->Game.input(Input input)->Player.input(Input input);
Framework.draw(Graphics2D g2d)->Game.draw(Graphics2D g2d)->World.draw(Graphics2D g2d);
How can I describe or call this "chaining/linking" the best? Becouse chaining in Java is like: Player.getLocation().setLocation(12,12).etc();
I hope my question is a little clear now,
thank you for your time in advance!
Edwin
I believe this is called the Delegator pattern

Error: Main method not found in class... why am I getting this?

Before people start flagging this question as a duplicate, know that I took the time too look at similar questions, and found that the answers to other "Error: Main method not found in class..." were not clearly applicable to my situation (according to my limited understanding of java)
I'm trying to utilize a text to speech api. Eclipse isn't complaining about the following code until I try to compile:
package com.textToSpeech;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class FreeTTS {
private static final String VOICENAME_kevin = "kevin";
private String text; // string to speech
public FreeTTS(String text) {
this.text = text;
}
public void speak() {
Voice voice;
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice(VOICENAME_kevin);
voice.allocate();
voice.speak(text);
}
public static void main(String[] args) {
String text = "FreeTTS was written by the Sun Microsystems Laboratories "
+ "Speech Team and is based on CMU's Flite engine.";
FreeTTS freeTTS = new FreeTTS(text);
freeTTS.speak();
}
}
The following error shows up in the console:
Error: Main method not found in class com.textToSpeech.FreeTTS, please define the main method as:
public static void main(String[] args)
The code above obviously has a main method, so does anyone know why I am getting this error, and furthermore how I can fix it?
I think it has something to do with the name of the class. If I change the name of the class to something like t2s and then try to compile, I get this error:
Error: Could not find or load main class com.textToSpeech.t2s
Anybody have any thoughts? Any help would be really appreciated.
You may have messed up your project properties. I don't use eclipse, so I cannot say for sure, but try creating a new project and adding the same code to it without fiddling with the properties. The class name and the file name should be the same, check that. Also make sure that the source file is in the same package folder. If nothing works, just create a new project.
Cheers.

global variables between different classes java

i am on the creation of an app in android. its a calculator app. the main activity is where the user could input the equation, and the second activity is where the user can add/edit/delete variables. so i made a new class in another file named Global.java. then i extended it to application, imported everything i need, made s private string, made some public functions, edited the manifest, and initialized it right on my main activity. everything works fine while im only using a string to be passed by the functions but when i started adding what i need, an ArrayList, and made some functions so i could access the list then run it, the app closes. i think its because the arraylist is not allowed to be passed to different classes? am i right or am i just missing something?
please dont downvote my post if i didn't post something needed. i am using aide so there is no log output. code:
Global.java
...
import android.app.*;
import java.util.*;
public class Global extends Application
{
private String s;
public static ArrayList<String> sList;
public String getS() {
return s;
}
public void setS(String ss) {
s=ss;
}
public void add() {
sList.add(s);
}
}
MainActivity.java
...
String s;
...
global=(Global)getApplicationContext();
...
global.setS("jian"); //this one works
global.sList.add("jian"); // this one dont
...
Are you sure you initialized sList, like this:
sList = new ArrayList<String>();
If you didn't, you might want to change its declaration to include this initialization.
public static ArrayList<String> sList = new ArrayList<String>();
Just do
global.add("jian");
since you have an add function to take care of the addition of item to arraylist.
Also, try with this:
public void add(String ss) {
sList.add(ss);
}
You are not instantiating your arraylist.
public static ArrayList<String> sList = new Arraylist<String>();
Also you should read beginner tutorials on Java and android, using a public extension of application like this is a bad idea and you can get log outputs from different apps if Aide doesn't provide that, search play store

Categories