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)
Related
package generics;
import java.util.ArrayList;
import java.util.List;
public class Generics {
private static List <Box> newlist = new ArrayList<>();
public static void main(String[] args) {
newlist.add(new Box("charlie",30));
newlist.add(new Box("max",29));
newlist.add(new Box("john",22));
// Testing method find -- Start
find ("max",29);
//Testing method find2 -- Start
Box <String,Integer> search = new Box("max",29);
find2(search);
}
public static void find (String parameter, Integer parameter1){
for (Box e : newlist){
if(e.getName() != null && e.getMoney() !=null
&& e.getName().equals(parameter)
&& e.getMoney().equals(parameter1)){
System.out.println("found on position " + newlist.indexOf(e));
break;
}
}
}
public static void find2 (Box e){
for (Box a : newlist){
if (a.equals(e)){
System.out.println("Found");
}else {
System.out.println("Not found");
}
}
}
}
public class Box<T , D>{
private T name;
private D money;
public Box(T name, D money) {
this.name = name;
this.money = money;
}
public T getName() {
return name;
}
public D getMoney() {
return money;
}
#Override
public String toString() {
return name + " " + money;
}
}
Can someone show me how to search for an object in ArrayList.
Method find() it works perfect but in my opinion is wrong and
the reason why I am thinking like that, because I am passing as parameter a string and an integer but should be an box object or maybe I wrong?
In my second method find2() I am trying to pass as parameter an object of Box and when I am trying to search for it I got a false result =(
I am noobie I am trying to understand and to learn.
Stop using raw types!
Box is generic, so if you are not targeting older Java versions, always add generic parameters!.
The declaration of find2 should be like this:
public static void find2 (Box<String, Integer> e)
And you should check whether two boxes are equal in exactly the way you did in find. equals will not work because you did not define an equals method in Box. So:
for (Box<String, Integer> a : newlist){
if (a.getName().equals(e.getName()) &&
a.getMoney().equals(e.getMoney())){
System.out.println("Found");
}else {
System.out.println("Not found");
}
}
You should override Object.equals() on the Box class.
Try to handle null correctly too. Because 2 Box with null names and/or null money are in fact equal.
(you DON'T need to override Object.hashCode() for this, but it's a good practice to do so, just in case it is used in a hashmap or hashset or such).
The easiest way to search and find something in an arraylist is to use the .equals method combined with a for loop to iterate through your lists.
for(int i = 0; i < newList; ++i)
{
if(newlist.equals(Stringname))
{
//it matches so do something in here
}
}
what it is doing here is moving through the list 1 by 1 until it finds something that matches what you entered -> stringName
I have a Class called Subject which will store some information like a subject name and a subject code, I'm struggling because what I'm trying to do is make it loop through the list of records in the arraylist and add the new record if it doesn't already exist. Please help, Ive tried searching for an answer on here but haven't seem to be able to find it.
If looping is not the right thing to do please point me in the right direction.
Thanks
//The Class
public class Subject {
private String name;
private String subjectCode;
public Subject(){
}
public Subject(String name, String subjectCode){
this.name = name;
this.subjectCode = subjectCode;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getSubjectCode(){
return this.subjectCode;
}
public void setSubjectCode(String subjectCode){
this.subjectCode = subjectCode;
}
//The Main method
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Subject> subjectList = new ArrayList<>();
//Test records
subjectList.add(new Subject("Java 1", "ITC101"));
subjectList.add(new Subject("Java 2", "ITC201"));
subjectList.add(new Subject("Java 3", "ITC301"));
String newGetName;
String newSubjectCode;
do {
System.out.print("Enter Subject Name: ");
newGetName = input.nextLine();
System.out.print("Enter Subject Code: ");
newSubjectCode = input.nextLine();
for(int i = 0; i < subjectList.size(); i++){
if(!subjectList.get(i).getName().contains(newGetName) && !subjectList.get(i).getSubjectCode().contains(newSubjectCode)){
subjectList.add(new Subject(newGetName, newSubjectCode));
} else {
System.out.println("We have a match ");
}
}
} while(!"0".equals(newGetName));
}
You are declaring a "no match" too soon: you need to walk the whole list before adding a new subject.
Your program tries the first subject, and if ut does not match, it adds a subject, and moves on. Unfortunately, it does not break, so it keeps adding the same subject for each existing one that does not match.
In order to fix this problem make a boolean variable called "found", set it to false before the loop, and search for matches. Once a match is found, set the variable to true, and break.
After the loop check your variable. If it's true, do not add, and say that you found a duplicate. Otherwise, add the new subject.
in your case, you can not check for 'contains' you have to manually check every entry if its the same.
override the equal() function of your Subject:
public boolean equal(Object o){
Subject b = (Subject) o;
return (this.name.equal(b.name) && this.code.equal(b.code));
}
then in your loop:
boolean found = false;
for(Subject s : subjectList){
if(s.equal(newSubject)){
found = true;
break;
}
}
if(!found) //add new entry
If Subject implements equals(), then create the object and call subjectList.contains(subject). Better yet, implement hashCode() too and change the ArrayList to a HashSet (or LinkedHashSet if order is important) for better performance.
Otherwise, search like this (using equals(), not contains(), for string comparison):
boolean found = false;
for (Subject subject : subjectList)
if (subject.getName().equals(newGetName) && subject.getSubjectCode().equals(newSubjectCode)) {
found = true;
break;
}
if (found)
System.out.println("We have a match ");
else
subjectList.add(new Subject(newGetName, newSubjectCode));
I wanted to pass the "result" of "You Chose : abc" to a return type, so I can then pass it into my serialized method, so that I can then serialize that chosen team. I know how to return an array, but how would I return an array -1 ?
Code snippets are as follows :
public class Display{
public String[] printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
System.out.println("You chose: " + clubName[choice - 1]); // return the clubName -1
}
return result; // how to declare return statement ?
}
}
Here is my serialize code, not sure how I would pass the array, via an alias or use object ?
public class Serialize
{
public void Serialize() // receive return type from printGreeting();
{
// how to put object info into files, rather than declare here ?
try
{
FileOutputStream fileOut = new FileOutputStream("/home/cg/root/club.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(club);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in C:/tmp/club.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Any help with this would be greatly appreciated :)
Here you declare to return an array of String[]:
public String[] printGreeting(int choice, String[] clubName) {
// ↑ here you say this method MUST return an array if Strings
What you need is
assign the user's choice to returned variable
return just ONE String
public String printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
// assign choice to result
result = clubName[choice - 1];
// print choice
System.out.println("You chose: " + result); // return the clubName -1
}
// return the chosen club name
return result;
}
Actually, I don't know why result is a class attibute (but i cannot see declaration), what does not make much sense if you want to return it, I will code the method as:
public String printGreeting(int choice, String[] clubName) {
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); // ??
if (choice >= 1 && choice <= 20) {
choice --; // if choice is valid, get the array position.
// print choice
System.out.println("You chose: " + clubName[choice]);
return clubName[choice];
}
// if the choice is not correct, return null or "" as you want
return null;
}
UPDATE
Could anyone advise how I would pass that returned String to my serialize method, I think I know how to serialize it, but not 100% sure on parameter passing.
I don't get exactly what you want to achieve, maybe would be better to rephrase question with your target clear, and your tries.
Serialize (shortly), in Java is make an object's attributes convertible to Strings, then, a String either an String[] array does not need to be serialized.
As long as Display methods are not static, you must create an instance of Display to execute as follow:
public class Main {
public static void main(String [] args) {
// create an instance of Display class
Display d = new Display();
// get the needed values to pass to printGreeting method:
String[] clubs = {"club one", "club two" // put 20 clubs
// get the index from the user
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int choice = sc.nextInt();
// call the method and get the return:
String result = d.printGreeting(choice, clubs)
// then get a serializer and execute method:
Serialize s = new Serialize();
s.serialize(result);
}
}
change the method Serialize.serialize() to Serialize.serialize(String) as follows:
public class Serialize
{
public void serialize(String club)
// ↑ receive return type from printGreeting();
{
// your serialize code
}
}
What do you want to return? The club name (String) or the whole array?
It's not clear in your code if result is an array or a String, you simply say result = clubName. If it's an array it should be String[] result = clubName;, if you want to return a String it should be String result = clubName[choice -1];, in that case you have to change the method to public String printGreeting(int choice, String[] clubName) and you can return result;
I have a program that allows the user to choose between a binary search tree a splay tree and a red black tree. I wrote the class for the binary search tree and now im working on the splay tree but ive realized that my method that interacts with the user only works with the binary search tree. I set it up so that it will create an instance of whichever tree the user selects but down in my code I use only the variable that would be created if the user selected a binary search tree. My question is how can i make it so that I will only create an instance of the tree that the user selected and how can i use only one variable so that when i insert items or work on the tree i dont have to add more conditional statements for different trees?
this is what i have now
import java.util.Scanner;
import java.lang.Math.*;
public class Driver1
{
public static void main(String[] args)
{
//local variables
String treeChoice = null;
String choice = null;
String choice2 = null;
String command = null;
int insertAmount = -1;
String pattern;
int height = -1;
int i = -1;
//BST<Integer> myTree = null;
//ST<Integer> mySTTree = null;
int num = 0;
//Scanners to take user input
Scanner input = new Scanner(System.in);
Scanner inputt = new Scanner(System.in);
System.out.println("Which tree would you like to test (BST, ST, RBT)? ");
treeChoice = input.nextLine();
//Based on user input either a BST, Splay Tree, or RBT will be initialized.
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
else if("ST".equalsIgnoreCase(treeChoice))
{
//System.out.println("Splay Tree not ready yet");
ST<Integer> mySTTree = new ST<Integer>();
}
else if("RBT".equalsIgnoreCase(treeChoice))
{
System.out.println("RBT not ready yet");
//RBT<Integer> myTree = new RBT<Integer>();
}
else
{
System.out.println("Invalid Entry");
}
//Ask user how many items to input
System.out.println("How many items would you like to insert? ");
insertAmount = input.nextInt();
//ask user if the items will be random or sorted
System.out.println("Pattern (random or sorted): ");
choice2 = inputt.nextLine();
//If random, create random numbers
if("random".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert((int)(Math.random()*1000000)+i);
}
}
//else fill the tree with numbers in order from 1 to the user limit
else if("sorted".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert(i);
}
}
//Keep asking users input on what to do to the tree until user says quit
while(command != "quit")
{
System.out.println(
"Next command (insert X, delete X, find X, height, quit)?");
command = inputt.nextLine();
if (command.startsWith("insert"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.insert(num);
if(result == false)
{
System.out.println("Item already present.");
}
}
else if(command.startsWith("delete"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.delete(num);
}
else if(command.startsWith("find"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.find(num);
if(result == true)
{
System.out.println("Item present.");
}
else
{
System.out.println("Item not present.");
}
}
else if(command.startsWith("height"))
{
System.out.println("Current height of tree " + myTree.height());
}
else if(command.startsWith("quit"))
{
break;
}
System.out.println();
}
}//Close main method
as you can see I fill only myTree which would be the tree created if the user selected bst. and in the while loop i only work on myTree.
How can i make this more generic or my other idea was to take the users input and then create the instance of that tree and then pass the instance into a seperate method so that i could still use only myTree since it would refer to the instance that was passed into that method but im not sure how to pass an instance into another method. This way seems like the best but im not sure
any help is appreciated
Your trees should extend a common base class, or better, a implement common interface, say Tree, that specifies the methods to be used on all trees (find, insert, delete). Then you should have only one variable Tree myTree to which you assign an actual instance of the type the user selects.
Are you sure your above code works, however? If you do this
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
then the variable myTree will be unavailable after the } because the code block in which it is declared ends there. You can declare a variable at one point and assign a value to it later, like so:
Tree<Integer> myTree;
if("BST".equalsIgnoreCase(treeChoice)) {
myTree = new BinarySearchTree<Integer>();
} else if("ST".equalsIgnoreCase(treeChoice)) {
myTree = new SplayTree<Integer>();
} else if("RBT".equalsIgnoreCase(treeChoice)) {
myTree = new RedBlackTree<Integer>();
} else {
throw new IllegalArgumentException(treeChoice + " is not a valid input");
}
I very much recommend that you give your classes real names that make obvious what they represent, not just two or three letter combinations. Note that if you do not throw an exception in the last else branch, the compiler will later complain that "the variable myTree may not have been initialized".
Alternatively, you could put all your code after the tree creation if-else-statements into a method, say <T> void testTree(Tree<T> myTree) and call this method directly where you evaluate the user input, e.g. if("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>());, but at some you will want to assign it to a variable anyway.
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!