Java static array modifications [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have two of the following java classes (listed below) Class BookInfo declares static block of arrays
public class BookInfo {
// Global arrays accessible by all methods
public static String[] isbnInfo;
public static String[] bookTitleInfo;
public static String[] authorInfo;
public static String[] publisherInfo;
public static String[] dateAddedInfo;;
public static int[] qtyOnHandInfo;
public static double[] wholesaleInfo;
public static double[] retailInfo;
static {
isbnInfo = new String[] {
"978-0060014018",
"978-0449221431",
"978-0545132060",
"978-0312474881",
"978-0547745527"
};
bookTitleInfo = new String[] {
"The Greatest Stories",
"The Novel",
"Smile",
"The Bedford Introduction to Drama",
"AWOL on the Appalachian Trail"
};
authorInfo = new String[] {
"Rick Beyer",
"James A. Michener",
"Raina Telgemeier",
"Lee A. Jacobus",
"David Miller"
};
publisherInfo = new String[] {
"HerperResource",
"Fawcett",
"Graphix",
"Bedford St. Martins",
"Mariner Books"
};
dateAddedInfo = new String[] {
"05/18/2003",
"07/07/1992",
"02/01/2010",
"09/05/2008",
"11/01/2011"
};
qtyOnHandInfo = new int[] {7, 5, 10, 2, 8};
wholesaleInfo = new double[] {12.91, 7.99, 6.09, 54.99, 10.17};
retailInfo = new double[] {18.99, 3.84, 4.90, 88.30, 14.95};
}
public static void BookInfo() {
System.out.println(" Serendipity Booksellers");
System.out.println(" Book Information\n");
for(int i = 0; i < isbnInfo.length; i++){
System.out.println("ISBN: " + isbnInfo[i]);
System.out.println("Title: " + bookTitleInfo[i]);
System.out.println("Author: " + authorInfo[i]);
System.out.println("Publisher: " + publisherInfo[i]);
System.out.println("Date Added: " + dateAddedInfo[i]);
System.out.println("Quantity-On-Hand: " + qtyOnHandInfo[i]);
System.out.println("Wholesale Cost: $ " + wholesaleInfo[i]);
System.out.println("Retail Price: $ " + retailInfo[i]);
System.out.println();
}
}
}
How do I access array list from this class? Only the following is working so far but how do I modify (add, delete, edit, etc) from this class (there is no main main in this class) BookInfo bookinfo = new BookInfo(); bookinfo.BookInfo(); System.out.println(bookinfo.isbnInfo[0]); how do I modify (add, delete, edit, etc) from the main menu
import java.util.Scanner;
public class InvMenu {
public static void addBook(){
System.out.println("\nYou selected Add a Book\n");
BookInfo bookinfo = new BookInfo();
bookinfo.BookInfo(); // only these two are working but I cannot modify arrays at all
System.out.println(bookinfo.isbnInfo[0]);
}
public static void editBook(){
System.out.println("\nYou selected Edit a Book's Record\n");
}
public static void deleteBook(){
System.out.println("\nYou selected Delete a Book\n");
}
public static void printInvMenu(){
String choice;
int x = 0;
boolean b;
char letter;
boolean menu = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("Serendipity Booksellers");
System.out.println("Inventory Database\n");
System.out.println(" 1. Look Up a Book");
System.out.println(" 2. Add a Book");
System.out.println(" 3. Edit a Book's Record");
System.out.println(" 4. Delete a Book");
System.out.println(" 5. Return to the Main Menu\n");
do{
System.out.print("Enter your choice: ");
choice = keyboard.nextLine();
b = true;
try {
x = Integer.parseInt(choice);
System.out.println(x);
}
catch(NumberFormatException nFE) {
b = false;
System.out.println("You did not enter a valid choice. Try again!\n");
}
}while(b == false);
do{
else if(x == 1){
addBook();
}
else if(x == 2){
editBook();
}
else if(x == 3){
deleteBook();
}
else if(x == 4){
System.out.println("Returning to the Main Menu\n");
break;
}
else{
System.out.println("\nYou did not enter a valid choice. Try again!\n");
}
printInvMenu();
}while(x == 5);
}
}
I can easily access some of the functionality from the other class main menu: BookInfo bookinfo = new BookInfo(); bookinfo.BookInfo(); System.out.println(bookinfo.isbnInfo[0]); How do I modify (add, delete, edit, etc) from the main menu? Any ideas, suggestions are greatly appreciated!

You simply can not "add" a new element to an Array after you have created it. From oracle tutorials page:
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Thus, if you want to add and remove elements from a List I recommend you to use an ArrayList object, which can be defined as a
Resizable-array implementation of the List interface.
You could for example replace your line of code
private static String[] isbnInfo;
for
private static ArrayList<String> isbnInfo;
and initialize it like:
isbnInfo = new ArrayList<String>()
isbnInfo.add("978-0060014018");
isbnInfo.add("978-0449221431");
isbnInfo.add("978-0545132060");
isbnInfo.add("978-0547745527");
As for edit your array, you can simply add some public getters for your private fields
public static String[] getIsbnInfo()
{
return isbnInfo;
}
and in your public class:
String[] isbnInfo = BookInfo.getIsbnInfo();
You can also use a public method to edit your arrays, like:
public static void replaceIsbnInfo(int index, String isbn)
{
isbnInfo[index] = isbn;
}
And in your menu class
BookInfo.replaceIsbnInfo(1, "978-0547745527");
I hope it helped. Cheers!

You've kind of mucked this thing up.
You should first create a "BookInfo" class (but not the one you defined) that contains instance fields of isbnInfo, bookTitleInfo, authorInfo, etc. (Just one entity for one book per field, not an array.)
Then, for each book, create and initialize the corresponding BookInfo object.
Next, either place the collection of such BookInfo objects in a searchable object such as a HashMap (for a single search field), or place them in an array of some sort and build separate HashMaps or whatever to map from search arguments to array index (anchoring all the pieces in a "Library" object).
When someone searches for a book, return the BookInfo object, which can have "getter" methods to extract the (ideally private) instance field values. This returns all info about the book in one piece.

You've declared the arrays as private, so they are private. You would have to write +accessor methods+ to return the respective arrays, or more elegantly write methods that access, search, modify, etc individual array entries.

If i understand correctly, you want to access values of an array, or any variable/function for that matter from a different class file?
ClassName.VariableName = whatever;
when you use
ClassName variable = new ClassName();
it runs that class every time you call it.make sure your variable is
public static VariableType Variablename;
or you wont be able to call/change it

ArrayList seem to be the most flexible out of all the options.
Even Effective Java 2nd Edition, Item 25: Prefer lists to arrays. Thanks for all your input!

Related

Java - How to find and remove an element in an ArrayList made of a custom class using one of that classes attributes

I am trying to find and remove an element from my ArrayList list (made from a custom master class ShoppingBasket) based on a user inputted String itemSearch whereby they would enter say Apple if they wanted to remove that from the basket, regardless of if the quantity is higher than 1.
The project is setup so that I have a masterclass ShoppingCart, with several subclasses Fruit, Dairy. Each class has a itemName and itemQuantity attribute.
Here is my Fruit class:
public class Fruit extends ShoppingBasket {
Fruit(String itemName, int itemQuantity){
super(itemName, itemQuantity);
}
}
Here is my Dairy sub-class code:
public class Dairy extends ShoppingBasket{
Dairy(String itemName, int itemQuantity){
super(itemName, itemQuantity);
}
}
For my ShoppingCard class I have hard-coded examples of instances of the Fruit and Diary classes and added them to a list to use as test data. I then try to iterate through that list and check each item against the name of the item the user has inputted and when it has found the correct item I try to remove it and print out the result. However, when it goes to print out the result, the program has not removed the item. When Debugging and using a Stop point I notice the program does not enter the if statement.
Below is the code for the master ShoppingBasket class:
import java.util.*;
import javax.swing.plaf.basic.BasicComboBoxUI.ItemHandler;
public class ShoppingBasket {
public String itemName;
public int itemQuantity;
static String itemSearch;
ShoppingBasket(String itemName, int itemQuantity){
this.itemName = itemName;
this.itemQuantity = itemQuantity;
}
public static void main(String[] args) {
List<ShoppingBasket> list = new ArrayList<ShoppingBasket>();
list.add(new Fruit("Apple", 2));
list.add(new Fruit("Orange", 4));
list.add(new Dairy("Semi-Skimmed Milk", 1));
list.add(new Dairy("Full Fat Milk", 3));
Scanner scnr = new Scanner(System.in);
System.out.println("What is the item that you want to remove from your basket? ");
itemSearch = scnr.nextLine();
for(ShoppingBasket s: list){
if(s.getItemName() != null && s.getItemName().contains(itemSearch)){
list.remove(itemSearch);
}
}
System.out.println(list.toString());
}
public String toString() {
return "Item name: " + this.itemName + " | Quantity: " + this.itemQuantity;
}
public String getItemName(){
return itemName;
}
}
Any help or hints of where I am going wrong would be appreciated. I apologise if this code is messy, I am new and trying to grasp the basics like Super Class and Sub Classes as well as other concepts of Java.
The clear mistake on your code was the line below:
list.remove(itemSearch);
You used the itemSearch String variable to remove the element from the list which was wrong. You should supply the element you want to delete to the remove method.
SOLUTION
To fix it you can simply replace the line mentioned above with:
list.remove(s);
In java 8 or above you can try the solution below with java streams:
List<ShoppingBasket> filteredList = list.stream()
.filter(shoppingBasket -> shoppingBasket.getName() != null && !shoppingBasket.getItemName().containsIgnoreCase(itemSearch))
.collect(Collectors.toList());
Use this to remove instead:
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getItemName() != null && list.get(i).getItemName().contains(itemSearch)) {
list.remove(list.get(i));
}
}

Finding specific instance of class? [duplicate]

This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 5 years ago.
I've just started learning java and I'm trying to create an application to register students.
Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.
public class RegStudent {
ArrayList<Student> studentList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void reggaStudent(int start) {
while (start != 0) {
String programNamn, studNamn;
int totalPoint, antalKurser;
System.out.println("Vad heter programmet?");
programNamn = input.nextLine();
System.out.println("Vad heter studenten");
studNamn = input.nextLine();
System.out.println("Hur många poäng har studenten?");
totalPoint = input.nextInt();
System.out.println("Hur många kurser är studenten registrerad på?");
antalKurser = input.nextInt();
// Add student to list of students
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
System.out.println("Vill du registrera in en fler studenter? "
+ "Skriv 1 för ja och 0 för nej");
start = input.nextInt();
input.nextLine();
} // End of whileloop
}
}
The class is:
public class Student {
private int totalPoint;
private int antalKurser;
private String programNamn;
private String studNamn;
private static int counter;
public Student(int totalPoint, int antalKurser, String program, String studNamn) {
this.totalPoint = totalPoint;
this.antalKurser = antalKurser;
this.programNamn = program;
this.studNamn = studNamn;
counter++;
}
public int getTotalPoint() {
return totalPoint;
}
public void setTotalPoint(int totalPoint) {
this.totalPoint = totalPoint;
}
public int getAntalKurser() {
return antalKurser;
}
public void setAntalKurser(int antalKurser) {
this.antalKurser = antalKurser;
}
public String getProgramNamn() {
return programNamn;
}
public void setProgramNamn(String programNamn) {
this.programNamn = programNamn;
}
public String getStudNamn() {
return studNamn;
}
public void setStudNamn(String studNamn) {
this.studNamn = studNamn;
}
public static int getCount(){
return counter;
}
#Override
public String toString() {
return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
+ "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
}
}
How do I go about to get and set the instance variables in specific instance? I.e find the instances.
I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.
I've added a counter just to see I actually created some instances of the class.
You simply query objects for certain properties, like:
for (Student student : studentList) {
if (student.getProgramName().equals("whatever")) {
some match, now you know that this is the student you are looking for
In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.
Alternatively, you could "externalize" a property, and start putting objects into maps for example.
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
You now have your Student objects in a list. I assume you have something like
List<Student> studentList = new ArrayList<>();
somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?
Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.

Library System: Borrowing

I do not know how to do the borrowHolding() in the Library Menu I have to create.
So the purpose of the borrowHolding() is for members to be able to borrow books or videos.
This is a just a sample data of the array:
member[0] = new StandardMember("ID", "Name");
member[1] = new PremiumMember("ID", "Name");
holding[0] = new Book("ID", "Title");
holding[1] = new Video("ID", "Title", loanFee);
This is the borrowHolding() method in the TestLibrary class: (the array is in the TestLibrary class too)
public static void borrowHolding(){
String option;
option = input.next();
do{
Scanner scan = new Scanner(System.in);
int tempId = 0;
System.out.println("Enter your ID: ");
String searchID = scan.next();
for(int i = 0; i < member.length; i++){
if(member[i].getID().equals(searchID)){
tempId = i;
}
}
So for the method, I tried to write a code that will search through the array to find the memberID that wants to borrow. It is not completed yet because I believe I am not doing it correctly
There is a Member class that contains
public class Member{
public Holding[] getCurrentHoldings(){
}
}
from the name of the method, it is used to store the holdings of the members that borrowed. So if member 1 borrows a book, that book will be stored inside the array, i think. I was thinking of using an ArrayList for this method, but not sure if it would make sense.
To borrow a book or video, there are certain conditions to be able to borrow, but I do not know how to implement this into the borrowHolding(). One of the condition are in the Holding class.
public class Holding{
public boolean borrowHolding(){
if(status == true && isOnLoan() == false)
borrowDate = newDateTime(); //this is to get the time when the book or video is borrowed
return true;
}else
return false;
}
}
And there is another condition in the Member class is that the Member must have enough credit to borrow. A book loan fee will cost $10 and a video will vary from $4 or $6.
I think I wrote a few information that is not needed but I guess its better than less information.
My problem is what do I do to the borrowHolding() method in the LibraryMenu? how do I make that if a member wants to borrow a holding, the holding will go under the member's array in the member class
public class Member{
public Holding[] getCurrentHoldings(){
}
}
with the condition from the holding class if it is met, and while executing the borrowHolding method, the method from the member class will be able to subtract the member credit by the loan fee from the book or video. is it possible?
public class Member{
private int credit = 30;
public int calculateRemainingCredit(){
credit = credit - //(the loan fee from the book or video class)
}
}
If your intentions are to add a holding to the member class then this is possible. I would suggest adding an ArrayList of Holding's rather than a regular array because it seems as if the size is going to be constantly changing.
public class Member{
private ArrayList<Holding> currentholdings; // you may need to import the arraylist
private int credit;
public void init(){ // goes in constructor
currentholdings = new ArrayList<Holding>();
credit=0;
}
public void addHolding(Holding newholding){ // adds a new holding to the members array
currentholdings.add(newholding);
credit-=newholding.getFee(); // will need to add a fee variable to the holding class;
}
}
And as for checking to see whether or not the member has enough "credit", that can be done in the borrowHolding() method right after you identify the index of the array. I would just recommend adding a parameter of the member to the borrowHolding() method so you can easily access the variables from that member.
if(member[i].getID().equals(searchID)){
tempId = i;
int tempHolding; // index of whatever holding you wanted (could get this from the scanner)
if (holding[tempHolding].borrowHolding(member[tempId])){ // check status
member[tempId].addHolding(holding[tempHolding]); // they have passed the req. so you can add the holding
}
break;
}
Hope this answered your question.

Retrive and compare int value from an ArrayList

good night. I'm trying to retrieve and compare an int variable value from an ArrayList (if that is possible) but no matter what I do it never works. I already tried methods like contains(), get() and others. My logic is really bad I guess, could someone help me ? Please?
public class Obras extends Books implements ILibrary {
protected ArrayList<Obras> ListObra = new ArrayList<Obras>();
protected String typeObra;
protected String statusBorrow;
protected int ISBNuser;
Scanner userInput = new Scanner(System.in);
Scanner tipoInput = new Scanner(System.in);
public void createnewObra()
{
System.out.println("Insert the type of the new item: [Book, article...");
typeObra = tipoInput.nextLine();
super.createnewObra();
}
....
public void addObra() {
Obras newObra = new Obras();
newObra.createnewObra();
ListObra.add(newObra);
System.out.println("> Uma nova obra foi adicionada com sucesso!\n");
....
public void BorrowObra() {
System.out.println("> Choose a book from the list: ");
showListObras();
System.out.println("\n\n> Please choose one of the items from the above list by typing it's ISBN value: ");
ISBNuser = opcaoInput.nextInt();.
if(ListObra.get(ISBN).equals(ISBNuser))
{
System.out.println("> You successfully borrowed this book");
statusBorrow = false;
}
To get an int from an ArrayList, your ArrayList would have to be defined along the lines of this:
ArrayList<Integer> arrayListOfIntegers = new ArrayList<Integer>();
or
List<Integer> listOfIntegers = new ArrayList<Integer>();
Your list appears to contain objects of class Obras.
Also, when you call ListObra.get(ISBN), this method is designed to return the object at the specified index within the list - I suspect ISBN is not an index in the list, rather an ISBN of a book?
On a separate note, try to stick to Java naming standards - variables start with lower case letters and methods use camel case (e.g. createNewObra()). It makes things easier for other developers to understand.
ListObra.get(ISBN).equals(ISBNuser)
to:
Obras o = ListObra.get(ISBN);
if (o != null && o.getISBNuser() == ISBNuser) {
System.out.println("> You successfully borrowed this book");
statusBorrow = false;
}
because you only get a object Obras and you doesn't Override equal function in Obras, so you need to get Integer ISBUser and equal to the user input.
Another Way:
Override equal:
public class Obras extends Books implements ILibrary {
#Override
public boolean equals(Object e) {
Integer i = (Integer)e;
if (this.ISBUser == i) return true;
return false;
}
}
so now can use equals function to compare:
ListObra.get(ISBN).equals(ISBNuser)

Java - Increase the value of an int size method by 1 everytime the method is called

I'm stuck on this one question I can't get my head around. I need to write a method to increase the number of "votes" of a specific "act" by one and then print out the updated vote count for that specific act. I'm working with ArrayLists here as well to point out.
Here is the logic you want to follow:
1: Iterate through ArrayList of 'acts'
2: Check for specified 'act'
3: If 'act' equals specified 'act', add one to your counter variable (votes++)
This is as much information as I'll give out without code to show what you've tried!
You could use a Map:
Class VoteCounter {
Map<Integer, Integer> actToCounterMap = new HashMap<Integer, Integer>();
public void raiseVoteForAct(int actId) {
if (actToCounterMap.contains(actId) {
int curVote = actToCounterMap.get(actId);
curVote++;
actToCounterMap.put(actId, curVote);
} else {
// init to 1
actToCounterMap.put(actId, 1);
}
}
}
You can print entire objects out in java, such as
System.out.println("Array list contains: " + arrayListName);
which will print the contents of the array without iterating through each value, although it may have odd syntax. As for the "acts", which I assume you mean objects, if you want to iterate the number of votes by one, you can have a class like this:
public class Act{
int votes = 0;
public void increaseVote(){
votes ++;
//You can also do votes = votes + 1, or votes += 1, but this is the fastest.
}
//While were at it, let's add a print method!
pubic void printValue(){
System.out.println("Votes for class " + this.getClass().getName() + " = " + votes + ".");
}
}
Finally, for a class with the arrayList:
class classWithTheArrayList {
private ArrayList<Act> list = new ArrayList<Act>();
public static void main(String[] args){
Act example1 = new Act();
list.add(example1);
//ArrayLists store a value but can't be changed
//when in the arraylist, so, after updating the value like this:
Act example2 = new Act();
example2.increaseVote();
//we need to replace the object with the updated one
replaceObject(example1, example2);
}
public void replaceObject(Object objToBeRemoved, Object objToReplaceWith){
list.add(objToReplaceWith, list.indexOf(objToBeRemoved); //Add object to the same position old object is at
list.remove(objToBeRemoved); //Remove old object
}
}
A slightly more efficient vote counter.
class VoteCounter<T> {
final Map<T, AtomicInteger> actToCounterMap = new HashMap<>();
public void raiseVoteForAct(T id) {
AtomicInteger ai = actToCounterMap.get(id);
if (ai == null)
actToCounterMap.put(id, ai = new AtmoicInteger());
ai.incrementAndGet();
}
}
Instead of AtomicInteger you can use new int[1] but it's relatively ugly. ;)

Categories