Declraring a global arrayList in Java - java

How do I declare a Global ArrayList accesible from all methods. I tried to declare it in main,in class, and various other places.
public static void InitializeTrips() {
public static List<Trip> TripList = new ArrayList<>();
TripList.add(new Trip(1, "NGP", "MUM", 3000, 1200, 1330));
TripList.add(new Trip(1, "MUM", "NGP", 3500, 1400, 1530));
}
public static void AddTrips() {
Scanner inpt = new Scanner(System.in);
int trpindx;String str;String end;int cst;int tmes;int tmee;
System.out.println("Please input the following :-");
System.out.print("Trip Index : "); trpindx = inpt.nextInt(); ;System.out.println("");
System.out.print("Source : "); str = inpt.next(); ;System.out.println("");
System.out.print("End : "); end = inpt.next(); ;System.out.println("");
System.out.print("Cost : "); cst = inpt.nextInt(); ;System.out.println("");
System.out.print("Departure : "); tmes = inpt.nextInt(); ;System.out.println("");
System.out.print("Arrival : "); tmee = inpt.nextInt(); ;System.out.println("");
}
public static void PrintTrips() {
System.out.print("Index Source Destination Depature Arrival Cost ");
.TripList.forEach(TripList -> {
System.out.println( ( TripList.getTRPINDX() )+ " " +(TripList.getSTR)+" "+(TripList.getEND)+" "+(TripList.getCST)+" "+(TripList.getTMEs)+" "+(TripList.getTMEe)+" "+(TripList.getDUR)+");
});

please try this sample code:-
package design.pattern;
import java.util.ArrayList;
public class GlobalAccessVariables {
public ArrayList<Trip> trips;
private GlobalAccessVariables() {
trips = new ArrayList<Trip>();
}
private static GlobalAccessVariables instance;
public static GlobalAccessVariables getInstance() {
if (instance == null)
instance = new GlobalAccessVariables();
return instance;
}
}
for access it in any class :
GlobalAccessVariables instance = GlobalAccessVariables.getInstance();
ArrayList tripsList = instance.trips;
tripsList.add("add trip here")
hope it will work for you

Related

I'm having a logic error on my program, the if statement works, but when a user inputs a bloodType & rhFactor it still shows O+ regardless of uinput

Here's the first part:
package Week5;
class BloodData
{
private String bloodType;
private String rhFactor;
public BloodData()
{
bloodType = "O";
rhFactor = "+";
}
public void setBloodType (String bloodType){
this.bloodType = bloodType;
}
public void setRhFactor (String rhFactor){
this.rhFactor = rhFactor;
}
String getBloodType(){
return this.bloodType;
}
String getRhFactor(){
return this.rhFactor;
}
}
here's the main method:
package Week5;
import java.util.Scanner;
public class RunBloodData
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BloodData bd = new BloodData();
System.out.print("Enter blood type of patient : ");
bd.setBloodType(input.nextLine());
System.out.print("Enter the Rhesus factor (+ or -) : ");
bd.setRhFactor(input.nextLine());
if(bd.getBloodType().equals("") && bd.getRhFactor().equals(""))
{
bd = new BloodData();
System.out.println (bd.getBloodType().toUpperCase() + bd.getRhFactor() + " is added to the bloodbank.");
}
else
{
bd = new BloodData();
System.out.println (bd.getBloodType().toUpperCase() + bd.getRhFactor() + " is added to the bloodbank.");
}
}
}
NOTE: I HIGHLY SUSPECT THAT I HAVE TO PUT SOMETHING INSIDE of new bloodData in:
else
{
bd = new BloodData();
I just don't know what to call considering bloodType and rhFactor are private and non-static.
I fixed it, I just had to remove bd = new BloodData(); in my else statement so any input will be registered.

ItemArray.checklist.add() not appending string to ArrayList

i have been learning java for around 3 days now but i cannot seem to append data to one of my ArrayLists (checklist). The output when attempting to show all items inside the array is always []. Help would be greatly Appreciated!
ShopAssist.java:
import java.io.*;
import java.util.Scanner;
class ShopAssist {
public static void main(String[] args){
//Items itemchecklist = new Items();
System.out.println("( Add | Remove | Show | Exit )");
System.out.print(">");
Scanner menuinput = new Scanner(System.in);
String choice = menuinput.nextLine();
if (choice.equals("Add")){
AddItem();
}
else if (choice.equals("Remove")){
RemoveItem();
}
else if (choice.equals("Show")){
ShowItems();
}
while(true){
main(null);
}
}
public static void AddItem(){
Items ItemArray = new Items();
System.out.print("Add: ");
Scanner addinput = new Scanner(System.in);
String addchoice = addinput.nextLine();
ItemArray.checklist.add(addchoice);
System.out.println("Info: " + addchoice + " has been added to checklist!");
}
public static void RemoveItem(){
System.out.println("RemoveItem Method");
}
public static void ShowItems(){
Items ItemArray = new Items();
System.out.println("ShowItems Method");
System.out.println(ItemArray.checklist);
}
}
Items.java:
import java.util.ArrayList;
public class Items {
ArrayList<String> checklist = new ArrayList<String>();
}
You create multiple instances of ItemArray.
Both in AddItem() and ShowItems().
So you never use the same instance in these methods.
It should be written once :
Items ItemArray = new Items();
and be either a passed parameter to these methods or a field of the class.
And ideally, this should be a private instance field and you should change your static methods into instance methods :
class ShopAssist {
private Items items = new Items();
...
public static void main(String[] args){
ShopAssist shopAssist = new ShopAssist();
while (true) {
System.out.println("( Add | Remove | Show | Exit )");
System.out.print(">");
Scanner menuinput = new Scanner(System.in);
String choice = menuinput.nextLine();
if (choice.equals("Add")) {
shopAssist.addItem();
}
else if (choice.equals("Remove")) {
shopAssist.removeItem();
}
else if (choice.equals("Show")) {
shopAssist.showItems();
}
}
}
public void addItem(){
...
}
...
public void showItems(){
System.out.println("ShowItems Method");
System.out.println(items.checklist);
}
...
}
Using static everywhere is not OOP.

How do I make a list of new elements?

I want to make a list of elements create with user input. Can I directly store an element into a list, or do I have to create a reference? I found how to make a list of premade variables, but I want to create te variables with user input.
The goal of my project is to store dataset and recall them at a later moment.
First I understand the concept of lists. Therefore I don't think its useful to copy my code at this moment.
import java.util.*;
public class Database {
public Database () {
}
public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Add a new spawnpoint.\n");
System.out.println("State the name of this spawnpoint: ");
Spawnpoints Sp1 = new Spawnpoints(getSpawnName());
System.out.println("Name: " + Sp1.getSpawnName());
System.out.println("Location: " + Sp1.getLocation());
System.out.println("Pokemon: " + Sp1.getPokemon());
System.out.println("Spawntime: " + Sp1.getSpawntime());
System.out.println("The pokemon is currently spawned: " + Sp1.isSpawned());
numberOfSpawnpoints++;
}
public static String spawnName;
public static String getSpawnName() {
spawnName = userInput.next();
return spawnName;
}
public void setSpawnName(String spawnName) {
Database.spawnName = spawnName;
}
}
Hope this helps
import java.util.*;
public class Database {
public Database () {
}
public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Add a new spawnpoint.\n");
System.out.println("State the name of this spawnpoint: ");
ArrayList<Spawnpoints> SPlist = new ArrayList<Spawnpoints>();
SPlist.add(new Spawnpoints(getSpawnName()));
// the above line will create an object of Spawnpoints and store it in list
System.out.println("Name: " + SPlist.get[0].getSpawnName());
System.out.println("Location: " + SPlist.get[0].getLocation());
System.out.println("Pokemon: " + SPlist.get[0].getPokemon());
System.out.println("Spawntime: " + SPlist.get[0].getSpawntime());
System.out.println("The pokemon is currently spawned: " + SPlist.get[0].isSpawned());
numberOfSpawnpoints++;
}
public static String spawnName;
public static String getSpawnName() {
spawnName = userInput.next();
return spawnName;
}
public void setSpawnName(String spawnName) {
Database.spawnName = spawnName;
}
}
You can try adding this code:
ArrayList<String> items = new ArrayList<String>();
while (!userInput.equals("exit")){
items.add(userInput.next());
}

Modify class to write exceptions to text file

I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

Adding user input to ArrayList using do-while loop

I am trying to add user input to an Arraylist using a do-while loop however I keep ending up with a list consisting of only the final item inputed repeated several times.
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while(!response.equals("done"));
return toBuy;
}
should work as mentioned in my comment.
Please implement a toString() method in your Item class if not done already.
you should replace your System.out.println as following:
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
}
} while(!response.equals("done"));
for (Item item : toBuy){
System.out.println(item);
}
return toBuy;
}
if this doesn't helps, please share some more code.
Here is fully working example
package stackoverflow;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Q53837506 {
public static void main(String[] args) {
ArrayList<Item> purchaseItems = purchaseItems();
System.out.println(purchaseItems);
}
public static class Item {
String r;
int v;
public Item(String r, int v) {
super();
this.r = r;
this.v = v;
}
#Override
public String toString() {
return "Item [r=" + r + ", v=" + v + "]";
}
}
static final Random randGen = new Random();
public static ArrayList<Item> purchaseItems() {
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
Scanner in = new Scanner(System.in);
do {
response = in.nextLine();
if (!response.equals("done")) {
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while (!response.equals("done"));
return toBuy;
}
}

Categories