Java and ArrayLists - java

package test.arraylist;
import java.util.Scanner;
public class TestArraylist {
static Scanner keyboard = new Scanner (System.in);
static int how_many;
public static void main(String[] args) {
menu();
}
public static void menu()
{
System.out.println("1.L2C");
System.out.println("2.M2R");
int menu = keyboard.nextInt();keyboard.nextLine();
switch (menu){
case 1:
NewClass l2c = new NewClass();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
l2c.l2c.add(keyboard.nextLine());
System.out.println("values:"+l2c.getL2c());
}
break;
case 2:
NewClass r2p = new NewClass();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
r2p.r2p.add(keyboard.nextLine());
System.out.println("values:"+r2p.getR2p());
}
break;
}
}
public static void seats(){
System.out.println("values:"+r2p.getR2p()); // Error
System.out.println("values:"+l2p.getR2p()); // Error
}
}
---------------------------CLASS-----------------------
package test.arraylist;
import java.util.ArrayList;
public class NewClass {
ArrayList<String> l2c = new ArrayList<>();
ArrayList<String> r2p = new ArrayList<>();
public ArrayList<String> getL2c() {
return l2c;
}
public void setL2c(ArrayList<String> l2c) {
this.l2c = l2c;
}
public ArrayList<String> getR2p() {
return r2p;
}
public void setR2p(ArrayList<String> r2p) {
this.r2p = r2p;
}
}
I'm in java for only 2 weeks
In a few words, I'm going to explain what I'm trying to do.
I am creating an ArrayList, after this user is entering
values to Arraylist.
Once everything is done, I want to access data from another method and to make some math operations, I realized that I should use some sort of return, I have tried to do this, but it does not work.
I am definitely doing something wrong.Pls help to sort this out.I spent 2 days on this.

It seems what you need is the composition of the NewClass into your Main class i.e.TestArraylist , Read composition in java composition-in-java-example
Now your code should be like this,
public class TestArraylist {
static NewClass newClass = new NewClass();
---------
--------
public static void menu(){
case 1:
ArrayList<String> l2c = newClass.getL2c(); //this way you can access the data
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
l2c.add(keyboard.nextLine()); //here you need only the instance variable to add the data into the arraylist.
System.out.println("values:"+l2c.toString()); //to print the data
}
break;
//Same way you should modify the case2 as well.
case 2:
ArrayList<String> r2p = newClass.getR2p();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
r2p.add(keyboard.nextLine());
System.out.println("values:"+r2p.toString());
}
break;
Now that composite object will be accesible in you below method because we have declared it static.
public static void seats(){
System.out.println("values:"+newClass.getR2p()); // not throw any error
System.out.println("values:"+newClass.getR2p()); // not throw any error
}
Also your Newclass should be defined like this,
public class NewClass {
private ArrayList<String> l2c = new ArrayList<String>();
private ArrayList<String> r2p = new ArrayList<String>();
public ArrayList<String> getL2c() {
return l2c;
}
public void setL2c(ArrayList<String> l2c) {
this.l2c = l2c;
}
public ArrayList<String> getR2p() {
return r2p;
}
public void setR2p(ArrayList<String> r2p) {
this.r2p = r2p;
}
}
There are many things to be corrected but as of now to make your programm work , this should suffice.

If you call seats(), you will have an error because those variables are not declared within the proper scope. To make r2p and l2c available within that method, move the variable declarations outside of the method (below the class declaration, before main()) with the initializer private static NewClass newClass;. Feel free to assign a value as needed, or employ optionals (but considering you’ve only been doing Java for 2 weeks, stay away from optionals; just make sure you assign a value).
Edit: Use static modifier on the variables, since you’re accessing from a static context.

Related

ArrayList troubles

I was wondering how to reference an ArrayList a different method than it was declared in.
For example I am writing a program that allows me to create a playlist of songs, so in one method I have createAPlaylist and then another method I have shuffle().
In my playlist method I have created an ArrayList but I am having trouble using this arrayList in my shuffle method. There is some code below for context:
public static void createAPlaylist() {
try {
System.out.println("We have the following tracks:");
ArrayList<String> songs = new ArrayList<String>();
String firstSong = jukebox.allTracks.get(0).getTitle();
songs.add(firstSong);
for (int index = 0; index < count; index++) {
System.out.println(SPACES + (index + 1) + ". " + jukebox.allTracks.get(index).getTitle());
}
System.out.println("Select a track to add to the playlist: ");
int songNumber = input.nextInt();
String songSelected = songs.get(songNumber);
songs.add(songSelected);
input.nextLine();
} catch (Exception e) {
System.out.println("\nplease select a valid song number.");
}
}
This is what method parameters are for:
public static void createAPlaylist() {
ArrayList<String> songs = new ArrayList<>();
shuffle(songs);
}
public static void shuffle(ArrayList<String> songs) {
// Do stuff with your ArrayList here
}
You can the arraylist from the createAPlaylist method and pass that to shuffle method:
Like:
public static List<String> createAPlaylist() {
...
...
...
return songs;
}
/// and then in shuffle method receive that as parameter :
public static void shuffle(List<String> songs){
// access that songs list by
}
Or you could:
Instead of method variable declare that arraylist as class variable..
Like:
public class ClassName{
public static ArrayList<String> songs = new ArrayList<String>();
public static void createAPlaylist() {
...
...
...
// reset the songs.
songs = new ArrayList<String>();
...
}
/// and then in another method:
public static void suffle(){
// access that songs list by
List<String> createdSongs = ClassName.songs;
}
In Java, variables are only available within the context they are created - so if you create an ArrayList inside a method, you cannot access it outside of that method unless you store it in the method’s class, or you return the variable from the method it’s made it.
You can either declare the ArrayList outside of the method, as a class field, like so:
public class Foo {
private static ArrayList<String> arrayList = new ArrayList<String>();
public static void createAPlaylist() {
arrayList.add();
etc...
}
}
Or you could return the ArrayList from the method like so:
public class Foo {
public static void main(String[] args) {
ArrayList<String> arrayList = createAPlaylist();
}
public static ArrayList<String> createAPlaylist() {
ArrayList<String> songs = new ArrayList<String>();
// Your code here
// Note that you have to return the list from
// inside the catch block!
// I’d recommend creating the ‘songs’ ArrayList
// outside of the ‘try’ block, so that you can
// have a fallback if something fails in the ‘try’
return songs;
}
}
I don’t know if you intend to have this all static. I’d think it will work better as non static, but that’s a matter for another question, so I’ve left it as-is in the examples.
Sorry if this isn’t formatted perfectly - I’m on a mobile device and don’t have my IDE.

Java accessing another class not working

I am making a game that requires an update class to access a game class and a main class to access both of those. The problem I am having is that I need the update class to have an updated object of the game class but I get an error whenever I try and access the game class from the Update class [error occurs on newGame.test();]
ERROR: Exception in thread "main" java.lang.NullPointerException
at Updates.updateStats(Updates.java:17)
at Game.gameLoop(Game.java:24)
at Main.main(Main.java:14)
import java.util.Scanner;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Game newGame = new Game();
//Updates getUpdates = new Updates();
newGame.setupGame();
Game.isRunning=true;
newGame.gameLoop();
}
}
import java.util.Scanner;
public class Game {
static Scanner input = new Scanner(System.in);
Updates getUpdates = new Updates();
public Game(){
}
String goverment;
int happyness;
double money;
int population = 1000000;
public static boolean isRunning;
private int turn = 0;
public void gameLoop(){
while (isRunning){
getUpdates.updateStats();
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
public void setupGame()
{
System.out.println("Goverment: 1=Democracy 2=monarchy 3=dictatorship");
goverment = input.nextLine();
while (!goverment.equals("1")||!goverment.equals("2")||!goverment.equals("3")){
if (goverment.equals("1")){
happyness = 75;
money = 250000.0;
break;
}
else if (goverment.equals("2")){
happyness = 50;
money = 500000.0;
break;
}
else if (goverment.equals("3")){
happyness = 25;
money = 750000.0;
break;
}
else{
System.out.println("ENTER A VALID VALUE");
goverment = input.nextLine();
}
}
System.out.println("1");
}
public int getHappyness(){
return happyness;
}
public void test(){
System.out.println("MY NAME IS BOB");
}
}
import java.util.Scanner;
public class Updates {
static Scanner input = new Scanner(System.in);
public Updates(){
}
public Updates(Game newGame){
this.newGame = newGame;
}
Game newGame;
public void updateStats(){
newGame.test();
}
}
I'm sorry if this isn't very much help, but it's my first time answering a question on here.
I put your code into a test project to see where the issue was, and it seems you have a few errors.
I'll start with the Main class as it has the smallest issues.
You don't need to declare the scanner object here as it's never used. You're just allocating memory to an empty object.
Now, onto the Updates class.
Again, no need to declare a scanner here.
To use the object "newGame" you need to make sure you're making use of the Constructor:
public Updates(Game newGame){
this.newGame = newGame;
}
And not:
public Updates(){
}
Because the latter one won't set the Game object for you, and any time you access it you will get a nullpointer.
Finally, the Game class:
I'd make both the Scanner and the Updates objects private, as they're never used outside the class. If they are, make use of getters and setters.
In your Game constructor, you can actually create both the getUpdates and input objects, like so:
public Game() {
this.input = new Scanner(System.in);
this.getUpdates = new Updates(this);
}
That way whenever your game is initialized, you'll have them at the ready. As you can see, I put
new Updates(this)
which uses the Updates constructor I mentioned before. This should ultimately solve your issue.
For reference, here are the files I used/edited and it worked on my end:
Pastebin link

How can i access an object from another method in java?

I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.
Is there another way to do this that I probably missed? Am I messing something up? If not, how should I do this to get the same functionality as below?
private static void create() {
Scanner input = new Scanner(System.in);
int length,offset;
System.out.print("Input the size of the numbers : ");
length = input.nextInt();
System.out.print("Input the Offset : ");
offset = input.nextInt();
NumberList numberlist= new NumberList(length, offset);
}
private static void question(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a command or type ?: ");
String c = input.nextLine();
if (c.equals("a")){
create();
}else if(c.equals("b")){
numberlist.flip(); \\ error
}else if(c.equals("c")){
numberlist.shuffle(); \\ error
}else if(c.equals("d")){
numberlist.printInfo(); \\ error
}
}
While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically.
This example:
public class MyClass {
public static String xThing;
private static void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
private static void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
makeThing();
makeOtherThing();
}
}
Will work, however, it would be better if it was more like this...
public class MyClass {
private String xThing;
public void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
public void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
MyClass myObject = new MyClass();
myObject.makeThing();
myObject.makeOtherThing();
}
}
You would have to make it a class variable. Instead of defining and initializing it in the create() function, define it in the class and initialize it in the create() function.
public class SomeClass {
NumberList numberlist; // Definition
....
Then in your create() function just say:
numberlist= new NumberList(length, offset); // Initialization
Declare numberList outside your methods like this:
NumberList numberList;
Then inside create() use this to initialise it:
numberList = new NumberList(length, offset);
This means you can access it from any methods in this class.

How to access object fields in a loop?

I can access the planetName, but not the Surfacematerial,Diameter etc because they are not in the array and in the object. How do I access the objects in a loop and their respective fields?
import java.util.Scanner;
public class Planet {
private String[] planetName;
private String SurfaceMaterial;
private double daysToOrbit;
private double diameter;
public Planet(){
planetName=new String[8];
SurfaceMaterial="";
daysToOrbit=0;
diameter=0;
}
public Planet(String[] planetName, String SurfaceMaterial,double daysToOrbit, double diameter){
this.planetName=planetName;
this.SurfaceMaterial=SurfaceMaterial;
this.daysToOrbit=daysToOrbit;
this.diameter=diameter;
}
public void setPlanetName(){
Scanner in=new Scanner(System.in);
Planet solar[]=new Planet[8];
for(int i=0;i<solar.length;i++){
solar[i]=new Planet(planetName,SurfaceMaterial,daysToOrbit,diameter);
System.out.println("Enter Planet Name::");
planetName[i]=in.next();
System.out.println("Enter Surface Material");
SurfaceMaterial=in.next();
System.out.println("Enter Days to Orbit");
daysToOrbit=in.nextDouble();
System.out.println("Enter Diameter");
diameter=in.nextDouble();
}
for(int i=0;i<solar.length;i++){
System.out.println(planetName[i]);
System.out.println(this.SurfaceMaterial); //This returns only one value that has been entered at the last
}
}
}
public static void main(String[] args) {
Planet planet=new Planet();
Scanner input=new Scanner(System.in);
planet.setPlanetName();
}
}
just access like following
object[index].member ... // or call getter setter
in your case say the first member name is name .. so call like
staff[0].name // this will return BOB
The staff array is declared as local in the Constructor: Or if it is declared in the class context, you are hiding it. So declare the staff array in the class context and then initialize in the constructor:
class Test
{
public Full_time [] Staff;
public Test()
{
Staff = new Full_time [4];
Staff [0] = new Full_time("BoB", 2000, 70000);
Staff [1] = new Full_time("Joe", 1345, 50000);
Staff [2] = new Full_time("Fan", 3000, 80000);
}
}
And then, in the main function:
public static void main(String[] args) {
Tester t = new Tester();
t.staff[i].name = "A Name";
}
However, instead of accessing member field directly it is suggested to use getter or setter function like: getStaff(i) and similar.

How do you pass in an array from the main method to another method in java?

I have an array of Person in my main method, and I have to pass in that array to PlayGame() method in the class Game. How do you do that?
public class RollOff {
public static void main(String[] args) throws IOException{
int numPeople;
int a;
System.out.println("How many people will play the game?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
numPeople = Integer.parseInt(s);
if ((numPeople >= 2) && (numPeople <= 10)) {
Person[] p = new Person[numPeople];
for (a = 0; a < numPeople; a++) {
p[0] = new Person(a);
}
}
}
}
public class Game extends RollOff{
int numPeople;
int a;
void PlayGame() {
}
}
You need to use parameters to do that:
void playGame(Person[] p){
...
}
Now simply call
public static void main(String[] args){
...
game.playGame(p);
}
Because playGame is not a static method, you'll either need to make it static and call Game.playGame(p) or you'll need to create an instance of Game: Game game = new Game() followed by a call of game, as shown in the example above.
public void play(Person[] person) {
// code
}
// The call
play(person);
You can simply add a Person array parameter to the PlayGame
void playGame(Person[] personArray){//logic of the method}
Then all you have to do is call the playGame method from the main method by creating a new instance of the class Game
Game game = new Game();
game.PlayGame(p);
here "p" is your persons array.
The main class should create an instance of Game, and pass the array of players to the constructor:
Game game = new Game(p);
game.playGame();
The Game class should thus have the following field and constructor:
private Person[] players;
public Game(Person[] players) {
this.players = players;
}
Note that methods should start with a lower-case letter to follow Java naming conventions, and that your loop has a bug: it always sets the first element of the array instead of initializing every element.
Finally, give meaningful names to variables: players is much more readable than p.

Categories