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());
}
Related
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
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.
This is the parent class
public class Holding {
private String holdingId, title;
private int defaultLoanFee, maxLoanPeriod, calculateLateFee;
public Holding(String holdingId, String title){
this.holdingId = holdingId;
this.title = title;
}
public String getId(){
return this.holdingId;
}
public String getTitle(){
return this.title;
}
public int getDefaultLoanFee(){
return this.defaultLoanFee;
}
public int getMaxLoanPeriod(){
return this.maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the child class:
public class Book extends Holding{
private String holdingId, title;
private final int defaultLoanFee = 10;
private final int maxLoanPeriod = 28;
public Book(String holdingId, String title){
super(holdingId, title);
}
public String getHoldingId() {
return holdingId;
}
public String getTitle(){
return title;
}
public int getDefautLoanFee(){
return defaultLoanFee;
}
public int getMaxLoanPeriod(){
return maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getHoldingId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the menu:
public class LibraryMenu {
static Holding[]holding = new Holding[15];
static int hold = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int options = keyboard.nextInt();
do{
}
System.out.println();
System.out.println("Library Management System");
System.out.println("1. Add Holding");
System.out.println("2. Remove Holding");
switch(options){
case 1:
addHolding();
break;
default:
System.out.println("Please enter the following options");
}
}while(options == 13);
System.out.println("Thank you");
}
public static void addHolding(){
System.out.println("1. Book");
System.out.println("2. Video");
int input1 = input.nextInt();
switch(input1){
case 1:
addBook();
break;
case 2:
addVideo();
break;
default:
System.out.println("Please select the following options");
break;
}
}
public static void addBook(){
}
}
All i want is when a user wants to add a book, the user will type in the title and id for it and it will save into the array, and when it is done, it will go back to the menu. I cant seem to do it with my knowledge at the moment.
i tried to do this in the addBook() method
holding[hold] = new Book();
holding[hold].setBook();
the setBook method would be in the Book class, to complete the setBook, i have to make set methods for all the get method. But when i do this, the constructor is undefined.
public void setBook(){
System.out.println("Title: " + setTitle());
System.out.println("ID: " + setHoldingId());
System.out.println("Loan fee: " + setDefaultLoanFee());
System.out.println("Max Loan Period: " + setMaxLoanPeriod());
}
If there is anything wrong with my code, please feel free to say it to me :D
Thanks.
edit: After the user adds a book or video, when the user wants to print all the holdings, it will show the title, id, loan fee and max loan period. How do i do that?
edit2: Clean up a few parts that wasn't necessary with my question
I would suggest you to use "List of Object" concept in handling it.
1) You can define a List of Book object for example.
List<Book> bookList = new ArrayList<Book>();
2) Everytime when you hit AddBook() function, you can then do something like this.
//Create a temporary object of Book to get the user input data.
Book tempBook = new Book(holdingIDParam, titleParam);
//Add them to the list
bookList.Add(tempBook);
3) You can then use that list to your likings, whether to store them into a .txt based database or to use them throughout the program. Usage example:
bookList.get(theDesiredIndex).getBook() ...
I am not entirely sure of what you want but after paying focus on your bold text,this is what I can understand for your case. Feel free to correct me on your requirements if it doesn't meet.
Hope it helps :)
instructions:
write a class called TagMaker that prints out tags. supply methods to (a) set the name (b) set the organization (c) print tag with the name and organization (d) clear the name and organization (e) print a blank tag. then write a TagTester class to test the TagMaker class.
so i got the code to accept the user input and print out a tag...but i did it without a tester class (i'm scared of those, and it wasn't working when i tried using one. any suggestions there?) and i've tried experimenting with codes that would clear the scanner to print out a blank tag also but it kept messing up the program so i took it out.
this is what i have so far:
import java.util.Scanner;
//import java.util.Locale;
//import java.io.*;
public class TagMaker {
public static void main (String[] args)
{
Scanner scannerObject = new Scanner( System.in );
System.out.print("This program will print out a name tag");
System.out.println("for each delegate.");
System.out.println("Please enter first name:");
String first = scannerObject.next();
System.out.println("Please enter last name:");
String last = scannerObject.next();
System.out.println("Please enter organization or affilation:");
String org = scannerObject.next();
System.out.println("###### " + "Annual Conference" + " ######");
System.out.println("### NAME: " + first + " " + last + " ###");
System.out.println("################################");
System.out.println("### ORGANIZATION:" + org + "###");
System.out.println("###############################");
String junk = scannerObject.next();
}
}
public class TagMaker {
private String tagName;
private String organization;
public void setTagName(String tagName){
this.tagName = tagName;
}
public void setOrganization(String organization){
this.organization = organization;
}
public void clearTagName(){
this.tagName = "";
}
public void clearOrganization(){
this.organization = "";
}
#Override
public String toString() {
return "Tag [Name=" + tagName + "\n Organization="
+ organization + "]";
}
}
class TagTester{
public static void main(String args[]){
TagMaker customTag = new TagMaker(); //Creates a new tag
customTag.setTagName("Custom Name"); //Sets tag name to Custom Name
customTag.setOrganization("Custom Organization"); //Sets tag organization to Custom organization
customTag.clearTagName(); //Clears tag name
customTag.clearOrganization(); //Clears organization
System.out.println(customTag); //Prints tag name and organization
}
}
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;
}
}