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

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.

Related

Declraring a global arrayList in 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

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());
}

Getting the output from a arraylist

Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}
This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}

I can't figure out how to print Hire and Fire from Stack

import java.util.*;
import java.util.Stack;
class Person {
private String name;
private String SS;
public Person(String N, String S) {
this.name = N;
this.SS = S;
}
}
class Manager {
Scanner keyboard = new Scanner(System.in);
private Queue<Person> app = new Queue<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
public void Apply() throws QueueException {
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
app.enqueue(apply);
}
public void hire() throws QueueException {
if (!app.isEmpty()) {
hire.push(app.dequeue());
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
fire.push(hire.pop());
} else {
System.out.println("Nobody to fire");
}
}
}
public class Management {
public static void main(String[] args) throws QueueException, StackException{
Scanner keyboard = new Scanner (System.in);
Manager user = new Manager();
boolean test = true;
while (test){
System.out.print("Press \n\t1 ACCEPT APPLICANT");
System.out.print("\t2 Hire \n\t3 Fire \n\t4 Quit:");
int action = keyboard.nextInt();
String space = keyboard.nextLine();
if (action == 1){
user.Apply();
}else if (action == 2){
user.hire();
}else if (action == 3){
user.fire();
} else if (action == 4){
System.exit(0);
}
else{
System.out.println("Please try again.");
}
}
}
}
I can't figure out how I can print out the name and ssn of the person I just hired or fired. I tried using peek, but it's not working. Basically, the whole program is about whether to accept and application, hire or fire. If I accept an application, it will prompt for the user to enter their name and ss, and if I press hire/fire it should print out the name and ss of that person.
Youre defining the queue wrong.
Its more like: Queue<Person> app = new LinkedList<Person>();
and you need a print method. Here's the Manager class. The print is called in the the Management Class, and if you define Manager user = new Manager(); you're surly going to be looked at funny.
Remove all the Throws. They are not defined and are not used....
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
class Manager
{
Scanner keyboard = new Scanner(System.in);
//private Stack<Person> app = new Stack<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
Queue<Person> app = new LinkedList<Person>();
public void Apply()
{
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
//app.enqueue(apply);
app.add(apply);
}
public void hire()
{
if (!app.isEmpty())
{
hire.push(app.remove());
}
else
{
System.out.println("Nobody to hire.");
}
}
public void fire()
{
if (!hire.isEmpty())
{
fire.push(hire.pop());
}
else
{
System.out.println("Nobody to fire");
}
}
public void dump()
{
while(!app.isEmpty())
{
Person p = app.remove();
System.out.println(p.getName()+" "+ p.getSS());
}
}
}

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