JAVA. Searching a value and displays the data [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
'm currently making a purchase program. I'm almost halfway done on it, the only thing i need is. when i Press 1 for purchase it will give me an option to input the Item Code that i stored in my inventory. And then it respectively displays the datas or values corresponds on my inputted code based on my stored products on my inventory.
PS: im new in java and i know my codes are still basic cus im still learning java on my own. And my variables are not yet changed into Arraylist cus i just found out that Arraylist is much better than a plain Array in storing collection of data.
Any suggestions is highly appreciated and welcome. Would stick on using Arraylist or Array. not Hashset or etc.. Thank you Guys!
Hope you guys could help me. Thanks!

class Item {
public final int sku;
public final String desc;
public final type other_fields;
public Item(int s, String d, type fields...) {
// set fields
}
}
or if you really want to be clever
abstract class Item {
public final int sku
// ....
}
class PinkCurtains extends Item {
public PinkCurtains() {
sku = 129534;
desc = "Adorable Pink Indoor Curtains";
}
}
class FuzzyTowel extends Item {
public FuzzyTowel() {
sku = 874164;
desc = "Machine Washable Fuzzy Towel";
}
}
then populate your list and search away
ArrayList<Item> catalog = new ArrayList<Item>(0);
for (int i = 0; i < numItems; i++) {
catalog.add(new Item(arg, arg, arg...));
}
// or
catalog.add(new PinkCurtains());
catalog.add(new FuzzyTowel());
for (Item item : catalog) {
if (chosenItem == item.sku) {
// do all your stuff
}
}
They are called Iterables for a reason. You don't have to make classes if you don't want to. ArrayList also has searching methods, contains() and indexOf() for example:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
If you want to fill in the fields as you go you can make a class that lets you do that:
class Item {
public int id;
public float price;
}
ArrayList<Item> cart = new ArrayList<Item>(0);
do {
Item item = new Item();
item.id = userInput;
item.price = userInput;
cart.add(item);
} while (userInputting);
float total = 0;
for (Item i : cart) {
total += i.price;
}
// using a regular for loop instead of for-each
for (int i = 0; i < cart.size(); i++) {
Item item = cart.get(i);
// or search for something particular
if (item.id == searchID) {
System.out.println("found item " + item.id + " with price $" + item.price);
}
// equivalent to
if (ids[i] == searchID) {
System.out.println("found item " + ids[i] + " with price $" + prices[i]);
}
}
Each time the user wants to add an item, you just make a new one, fill in the fields and add it to the list.

Related

How to search for ID number in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
My problem is I need to make a program where you can search for an employee based on their ID number. Which needs to be something like "E1" or "E2". I am struggling to find a way to search for numbers and letters in the same object. It only works when I use just a number like 1 or 2 by using Int.
How can I store both a letter and integer in an object? Is there something similar to String that stores letters or Int that stores numbers but for both letters and numbers?
Ex. I can search for my employe already but their ID is currently just "1" or "2" or "3". I need to change it to "E1" or "E2" etc. But it wont work with String or Int.
I am searching an array. In an employee class
You can check, if two Strings are equal, by using the equals method: String1.equals(String2);
Also, you could implement a new class implementing the interface Comparable. In this class you could split the ID into a String and an Integer part:
public class EmployeeID implements Comparable {
String s = null;
Integer i = null;
public EmployeeID(String s, Integer i) {
this.s = s;
this.i = i;
}
#Override
public void equals(EmployeeID id) {
return new String(s + i).equals(new String(id.s + id.i));
}
#Override
public void compareTo(EmployeeID id) {
return new String(s + i).compareTo(new String(id.s + id.i));
}
}
Of course, if you do not need to compare elements (which can be useful for sorting), you can just implement this wrapper class without the comparable interface.
The equals method compares two ids and is not implemented in the Comparable interface, but the Object class, which is the superclass of every class.
No code provided so I'm guessing as to what you actually are trying to do.
public class SomeIds {
private String[] ids;
public boolean isPresent(String id) {
for (String element : ids) {
if (element.equals(id)) {
return true;
}
}
return false;
}
/**
* returns the index of the first element matching the id
* provided or -1 if it is not found
*/
public int indexOf(String id) {
for (int index = 0 ; index < ids.length ; ++index) {
if (ids[index].equals(id)) {
return index;
}
}
return -1;
}
}
Unfortunately, you won't be able to mix types (i.e. numbers and letters). You'll have to use a String for storage of the ID, in which case, you can use equals to search:
String searchTerm = "E1";
for (Employee employe : employeeArr) {
if (employe.getId() == searchTerm) {
System.out.println("Employe_ID: E" + employe.getEmployeId() +
"\narbetstitel: " + employe.getArbetsTitel());
}
}
Better yet, use a HashMap so you don't have to loop to find an employee:
HashMap<String, Employee> employees = new HashMap<>(); // String to store IDs
Employee e = new Employee();
employees.put("E1", e);
// To fetch an employee
Employee e1 = employees.get("E1");
if (e1 != null) {
System.out.println("Employe_ID: E" + e1.getEmployeId() +
"\narbetstitel: " + e1.getArbetsTitel());
}

Array does not show up when called? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
In my code I created a class called Inventory to store my information in an array. I created a method to add strings, and a method to display all the information stored in the array. Something went wrong along the way for my code will execute, but it will not show any of the information that I stored in the array, just a blank command window. Here is the man class.
public class Game {
public static void main(String[] args) {
Inventory playersInventory = new Inventory();
playersInventory.addInventory("Knife");
playersInventory.addInventory("Food");
playersInventory.addInventory("Water");
playersInventory.displayInventory();
}
}
and here is the Inventory class
public class Inventory {
private String[] inventoryItem = new String[10];
public void addInventory(String item){
int x = 0;
while (true) {
if (inventoryItem[x]== null){
item = inventoryItem[x];
break;
}
else {
x++;
}
}
}
public void displayInventory(){
int x = 0;
while (true){
if (inventoryItem[x] == null){
break;
}
else{
System.out.println(inventoryItem[x] + "\n");
x++;
}
}
}
}
The problem lies in this line:
item = inventoryItem[x];
The = evaluate the expression on the right and assigns the result to the variable on the left. So what you're doing there is assigning inventoryItem[x] to item.
In other words, you are not mutating the array, but assigning a new value to the parameter, which does practically nothing.
I guess you want to add the parameter into the array. So your assignment statement should be the other way around:
inventoryItem[x] = item;
Actually, to avoid confusion, just use an ArrayList!
public class Inventory {
private ArrayList<String> inventoryItem = new ArrayList<>();
public void addInventory(String item){
inventoryItem.add(item);
}
public void displayInventory(){
for (Sting item: inventoryItem) {
if (item != null) {
System.out.println(item + "\n");
}
}
}
}
Isn't that much cleaner?
Your line of code
item = inventoryItem[x];
should be
inventoryItem[x] = item;
You are assigning inventoryItem[x]; to item where as you need the reverse.
Assign value inventoryItem[x] = item;
You did not put the item in the array "inventoryItem", Hence no information was displayed.
Change your code to following to populate the array
if (inventoryItem[x]== null){
inventoryItem[x]=item ;
break;
}

Accessing an element of an object in an arraylist [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am working with an ArrayList of objects that contain multiple variables. For example:
// pseudo code
class Ticket {
int gameID
double price
int seatnumber
}
and I have an ArrayList of multiple Ticket objects and need to access them. I've looked at the javadoc and so far I have come up with
list.get(index).attribute
However I get a compile-error saying:
cannot find symbol
am I doing something wrong with the syntax?
here is my code:
public static void printGameMoney(ArrayList games, ArrayList tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
You code is "old-school", you should use typed-types, interfaces and new style for-loop:
public static void printGameMoney(final List<Game> games, final List<Ticket> tickets)
{
double total = 0;
for (final Ticket ticket : tickets)
{
final double tickMoney = ticket.getPriceOfTick();
total = total + tickMoney;
}
}
Also note this method is strange as it doesn't return anything.
If attribute is really one of your class member then please use as follow.
((Ticket) list.get(index)).attribute;
Start by putting semicolons after each field declaration:
class Ticket {
int gameID;
double price;
int seatnumber;
}
Also, show the exact code you're using instead of list.get(index).attribute.
List<Object> list = new ArrayList<Object>();
((Ticket)list.get(x)).attribute;
Use this instead:
public static void printGameMoney(ArrayList games, ArrayList<Ticket> tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
Basically, the change leads to ArrayList<Ticket> instead of simple ArrayList. This way you tell the compiler that objects inside your ArrayList are of Ticket type, therefore they have attributes you specified (e.g. priceOfTick).
Same goes for games, so if you have Game class, you should use ArrayList<Game> games.
You have to access like this ,list.get(i).price; not list.price.get(i);
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = list.get(i).price;
total = total + tickMoney;
}
Here problem is that with your deceleration of ArrayList
If you declare like ArrayList<Ticket> you need not to cast there while getting. Other wise you need a cast there. More over use for each loop.

Access the value from list in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is one of my class
class number11 {
String ab;
int i;
public number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
}
And in main method, I used
List<number11> n1= new ArrayList<number11>();
How can I access the value of integers and String contained in List? I do wish just to print them but to use further.
{Closed ,Thank you all}
Just loop over the list:
for (number11 n : list) {
String ab = n.ab;
int i = n.i;
//print ab and i
}
Note that number11 should be in CamelCase to follow Java's conventions: Number11.
From your question it seems you want list of your objects,
Before continuing, please create getters and setters, I've used them
Also your class name should be camelCase. Number11 is valid but not number11
You can fill the list using
List<number11> list = new ArrayList<number11>();
list.add(new number11("a",1));
list.add(new number11("b",2));
To access the members,
for (number11 n : list) {
String ab = n.getAb();
int i = n.getI();
}
like this
List<number11> n1= new ArrayList<number11>();
for(number11 n:n1){
System.out.println("String value: "+n.ab);
System.out.println("int value: "+n.i);
}
According to better coding standards.Follow the below rules
1.Change you class so that It starts with a camel case.
2.Change variables to private.
3.Add setter and getter methods
Assuming you have added values to the ArrayList you can read values by using code such as n1.get(0).ab or n1.get(0).i.
List l = new ArrayList<number11>();
l.add(new number11("x",1));
l.add(new number11("y",2));
for (number11 element : l) {
System.out.println(element.ab + " "+ element.i);
}
You might first want to add getter methods to your class number11.
e.g
public class number11{
String ab;
int i;
public number11(String ab,int i)
{
this.ab=ab;
this.i=i;
}
public int getI(){
return i;
}
public String getAb(){
return ab;
}
}
You need to obtain a reference to the particular object held inside the ArrayList via the get(index) method where index is the element number starting with 0. Simply call the getter methods to retrieve the values.
e.g
List<number11> n1= new ArrayList<number11>();
//Adding the object
n1.add(new number11("Test", 4));
//Retrieving the object.
number11 inst = n1.get(0);
//Retrieve and print the values
System.out.println(inst.getAb());
System.out.println(inst.getI());
For better convention change your class structure to,
class Number11 {
private String ab;
private int i;
public Number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
Access in this way.
List<number11> n1= new ArrayList<number11>();
if(n1!=null && n1.size()>0){
for (Number11 n : n1) {
String ab = n.getAb();
int i = n.getI();
//print ab and i
}
}
List<number11> n1= new ArrayList<number11>();
after adding values to this list n1 it will contains number11 type objects from index 0 to n-1, where n is number of element you added to list.
Then you can call what ever object as follows
n1.get(1) // this will return 2nd object in the list
It will contain ab and i
You can call them as follows
n1.get(1).getab // 2nd element ab value in list n1
n1.get(1).i // 2nd element i value in list n1
List Interface allows to:
Positional access — manipulates elements based on their numerical position in the list
MyClass obj = myList.get(24); //--get 25th item of a List<MyClass>--
Iteration access — extends Iterator semantics to take advantage of the list's sequential nature
for(MyClass obj : myList){ //-- go through all items of a List<MyClass> one by one--
int i = obj.someField;
}
Once you have your object, you can access its fields.

Retrieving a random item from ArrayList [duplicate]

This question already has answers here:
Randomly select an item from a list
(5 answers)
Closed 4 years ago.
I'm learning Java and I'm having a problem with ArrayList and Random.
I have an object called catalogue which has an array list of objects created from another class called item.
I need a method in catalogue which returns all the information on one of the itemobjects in the list.
The item needs to be selected at random.
import java.util.ArrayList;
import java.util.Random;
public class Catalogue
{
private Random randomGenerator = new Random();
private ArrayList<Item> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Item>();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
When I try to compile I get an error pointing at the System.out.println line saying..
'cannot find symbol variable anyItem'
anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.
Might want to re-write it like:
import java.util.ArrayList;
import java.util.Random;
public class Catalogue
{
private Random randomGenerator;
private ArrayList<Item> catalogue;
public Catalogue()
{
catalogue = new ArrayList<Item>();
randomGenerator = new Random();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item item = catalogue.get(index);
System.out.println("Managers choice this week" + item + "our recommendation to you");
return item;
}
}
public static Item getRandomChestItem(List<Item> items) {
return items.get(new Random().nextInt(items.size()));
}
your print comes after you return -- you can never reach that statement. Also, you never declared anyItem to be a variable. You might want
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item randomItem = catalogue.get(index);
System.out.println("Managers choice this week" + randomItem.toString() + "our recommendation to you");
return randomItem;
}
The toString part is just a quickie -- you might want to add a method 'getItemDescription' that returns a useful String for this purpose...
Here you go, using Generics:
private <T> T getRandomItem(List<T> list)
{
Random random = new Random();
int listSize = list.size();
int randomIndex = random.nextInt(listSize);
return list.get(randomIndex);
}
You must remove the system.out.println message from below the return, like this:
public Item anyItem()
{
randomGenerator = new Random();
int index = randomGenerator.nextInt(catalogue.size());
Item it = catalogue.get(index);
System.out.println("Managers choice this week" + it + "our recommendation to you");
return it;
}
the return statement basically says the function will now end. anything included beyond the return statement that is also in scope of it will result in the behavior you experienced
try this
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
And I strongly suggest you to get a book, such as Ivor Horton's Beginning Java 2
anyItem has never been declared as a variable, so it makes sense that it causes an error. But more importantly, you have code after a return statement and this will cause an unreachable code error.
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
You havent the variable anyItem initialized or even declared.
This code:
+ anyItem +
means get value of toString method of Object anyItem
The second thing why this wont work. You have System.out.print after return statement. Program could never reach tha line.
You probably want something like:
public Item anyItem() {
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
btw: in Java its convetion to place the curly parenthesis on the same line as the declaration of the function.
As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.
See https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57
public static void main(String[] args) {
RandomList<String> set = new RandomList<>();
set.add("a", 10);
set.add("b", 10);
set.add("c", 30);
set.add("d", 300);
set.forEach((t) -> {
System.out.println(t.getChance());
});
HashMap<String, Integer> count = new HashMap<>();
IntStream.range(0, 100).forEach((value) -> {
String str = set.raffle();
count.put(str, count.getOrDefault(str, 0) + 1);
});
count.entrySet().stream().forEach(entry -> {
System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));
});
}
Output:
2.857142857142857
2.857142857142857
8.571428571428571
85.71428571428571
a: 2
b: 1
c: 9
d: 88
The solution is not good, even you fixed your naming and unreachable statement of that print out.
things you should pay attention also
1. randomness seed, and large data, will num of item is so big returned num of that random < itemlist.size().
you didn't handle multithread, you might get index out of bound exception
Here's a better way of doing things:
import java.util.ArrayList;
import java.util.Random;
public class facultyquotes
{
private ArrayList<String> quotes;
private String quote1;
private String quote2;
private String quote3;
private String quote4;
private String quote5;
private String quote6;
private String quote7;
private String quote8;
private String quote9;
private String quote10;
private String quote11;
private String quote12;
private String quote13;
private String quote14;
private String quote15;
private String quote16;
private String quote17;
private String quote18;
private String quote19;
private String quote20;
private String quote21;
private String quote22;
private String quote23;
private String quote24;
private String quote25;
private String quote26;
private String quote27;
private String quote28;
private String quote29;
private String quote30;
private int n;
Random random;
String teacher;
facultyquotes()
{
quotes=new ArrayList<>();
random=new Random();
n=random.nextInt(3) + 0;
quote1="life is hard";
quote2="trouble shall come to an end";
quote3="never give lose and never get lose";
quote4="gamble with the devil and win";
quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
quote13="No one can make you feel inferior without your consent.";
quote14="Let him who would enjoy a good future waste none of his present.";
quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
quote20="It is our choices, that show what we truly are, far more than our abilities.";
quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
quote22="The successful warrior is the average man, with laser-like focus.";
quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
quote27="Don’t let the fear of losing be greater than the excitement of winning.";
quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
quote29="There is nothing permanent except change.";
quote30="You cannot shake hands with a clenched fist.";
quotes.add(quote1);
quotes.add(quote2);
quotes.add(quote3);
quotes.add(quote4);
quotes.add(quote5);
quotes.add(quote6);
quotes.add(quote7);
quotes.add(quote8);
quotes.add(quote9);
quotes.add(quote10);
quotes.add(quote11);
quotes.add(quote12);
quotes.add(quote13);
quotes.add(quote14);
quotes.add(quote15);
quotes.add(quote16);
quotes.add(quote17);
quotes.add(quote18);
quotes.add(quote19);
quotes.add(quote20);
quotes.add(quote21);
quotes.add(quote22);
quotes.add(quote23);
quotes.add(quote24);
quotes.add(quote25);
quotes.add(quote26);
quotes.add(quote27);
quotes.add(quote28);
quotes.add(quote29);
quotes.add(quote30);
}
public void setTeacherandQuote(String teacher)
{
this.teacher=teacher;
}
public void printRandomQuotes()
{
System.out.println(quotes.get(n++)+" ~ "+ teacher);
}
public void printAllQuotes()
{
for (String i : quotes)
{
System.out.println(i.toString());
}
}
}

Categories