Array does not show up when called? [closed] - java

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

Related

Java ArrayList size() method return 0 instead of actual length of the ArrayList [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 last year.
Improve this question
I am learning Java and followed a tutorial like this:
package segovia.java.learn;
import java.util.ArrayList;
public class GroceryList {
private ArrayList<String> groceryList = new ArrayList<String>();
public void addGroceryItem(String item) {
groceryList.add(item);
}
public void printGroceryList() {
System.out.println("You have " + groceryList.size() + " items in your grocery list.");
for (int i=0; i < groceryList.size(); i++) {
System.out.println((i+1) + ". " + groceryList.get(i));
}
}
public int getLength(){
return groceryList.size();
}
}
package segovia.java.learn;
public class Main {
public static void main(String[] args) {
GroceryList myGroceries = new GroceryList();
myGroceries.addGroceryItem("apple");
myGroceries.addGroceryItem("orange");
myGroceries.addGroceryItem("pork");
myGroceries.addGroceryItem("beef");
myGroceries.printGroceryList();
System.out.println(myGroceries.getLength());
}
}
which worked fine. However, I thought that since the myGroceries is an ArrayList, so it should have the .size() method. So I added a line of
System.out.println(myGroceries.size());
but IntelliJ told me it's not working. So I thought that MAYBE I should use inheritance so I changed to
public class GroceryList extends ArrayList {
now the .size() method is working, but it gave me a wrong value.
Final codes are like this:
package segovia.java.learn;
import java.util.ArrayList;
public class GroceryList extends ArrayList{
private ArrayList<String> groceryList = new ArrayList<String>();
public void addGroceryItem(String item) {
groceryList.add(item);
}
public void printGroceryList() {
System.out.println("You have " + groceryList.size() + " items in your grocery list.");
for (int i=0; i < groceryList.size(); i++) {
System.out.println((i+1) + ". " + groceryList.get(i));
}
}
public int getLength(){
return groceryList.size();
}
}
package segovia.java.learn;
public class Main {
public static void main(String[] args) {
GroceryList myGroceries = new GroceryList();
myGroceries.addGroceryItem("apple");
myGroceries.addGroceryItem("orange");
myGroceries.addGroceryItem("pork");
myGroceries.addGroceryItem("beef");
myGroceries.printGroceryList();
System.out.println(myGroceries.getLength());
System.out.println(myGroceries.size());
}
}
and the getLenth() gave me 4, which is correct, while the .size() gave me 0, which is obviously wrong.
Can anyone help me understand why the codes work like this? I guess it's related to the class inheritance but not sure.
I think there is a misunderstanding of inheritance vs composition. In this case, before you added extends ArrayList to GroceryList, your GroceryList has a list. That's why .size() wasn't working on it, because the GroceryList you defined doesn't have a size method. It does have a list called groceryList though. That's why after you addGroceryItem, the getLength method works correctly. It's getting the size of groceryList.
After you added extends ArrayList, GroceryList now is an ArrayList, that's why it has a size method now. But it is not the same list as groceryList. Hence getting the size of myGroceries, after addGroceryItem doesn't give you the size you expected. Because you never added anything to the ArrayList that is myGroceries. You've only added thing to the groceryList that is a field in myGroceries.

Anyone can help to fix this run time error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Using arraylist and trying to get the last element, i am getting some runtime error.
import java.util.ArrayList;
public class MyProgram{
private ArrayList<String> list = new ArrayList<String>();
public void printLastThing(){
int lastIndex = list.size() - 1;
String thing = list.get(lastIndex);
System.out.println(thing);
}
public static void main(String[] args){
MyProgram example = new MyProgram();
example.printLastThing();
}
}
There are no elements added to the list and so it is empty. YOu are trying to fetch the element at -1 which will raise java.lang.IndexOutOfBoundsException.
In this case you should keep a check for going out of bounds.
I have added a method to check the lastindex. It will return -1 if list is emtpy and you can display that List if empty once you get -1.
import java.util.ArrayList;
public class MyProgram{
private ArrayList<String> list = new ArrayList<String>();
public MyProgram() {
list.add("a");
list.add("z");
}
public void printLastThing(){
int lastIndex = getLastIndex();
if(lastIndex >= 0)
System.out.println(list.get(lastIndex));
else
System.out.println("List is empty");
}
private int getLastIndex() {
if(list.size()==0) {
return -1;
}
return list.size() - 1;
}
public static void main(String[] args){
MyProgram example = new MyProgram();
example.printLastThing();
}
}

Receiving parameter for an array of objects from another class 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 6 years ago.
Improve this question
I am trying to create one array of objects of my class Percurso for another class Custos, but I don't know how to do this. Here is what is asking in the question:
Receives as parameter an array of path-type objects
My code :
Class Custos :
public class Custos {
public String calcularViagem(Percurso [] p) {
return "";
}
}
Class Percurso :
private double kmPercorrida;
private double valorCombustivel;
private double valorPedagio;
public double getKmPercorrida() {
return kmPercorrida;
}
public void setKmPercorrida(double kmPercorrida) {
this.kmPercorrida = kmPercorrida;
}
public double getValorCombustivel() {
return valorCombustivel;
}
public void setValorCombustivel(double valorCombustivel) {
this.valorCombustivel = valorCombustivel;
}
public double getValorPedagio() {
return valorPedagio;
}
public void setValorPedagio(double valorPedagio) {
this.valorPedagio = valorPedagio;
}
public Percurso() {
this(0,0,0);
}
public Percurso(double kmPercorrida, double valorCombustivel,
double valorPedagio) {
this.kmPercorrida = kmPercorrida;
this.valorCombustivel = valorCombustivel;
this.valorPedagio = valorPedagio;
}
How can I do this ? If someone can help, I will thanks.
PS: Before someone say that this post is similar to other questions about array, it's not,I looked for questions similar that could help and I didn't found any that really could help me.
Creating an array of Percurso objects is the same as creating an array of any object. To create the array, you will need to include a line like this:
Percurso[] percursoArray = new Percurso[LENGTH]; //with your own array name and length
However, that just creates an array; it doesn't put anything in it. To put Percurso objects in the array (or, more accurately references to the objects), you need code like this.
percusoArray[0] = new Percurso(5, 2, 1);
percusoArray[1] = new Percurso(1, 1, 1); //etc
Or, if the array is long, you could create the objects in a for loop:
for (int i = 0; i < LENGTH; i++){
percusoArray[i] = new Percurso(1,2,3); //with your own values
}
Of course, a question remains-- where should you put this code? Is the array of Percurso an attribute of Custos? If so, you might create the array as a class variable of Custos and populate it in the constructor for Custos. If it's not an attribute of Custos, but rather just a parameter for one of Custos methods, you'll need this code in whichever part of your code calls calcularViagem(), whether that is another method in Custos, a method in another class, or from inside your main method.

Why am i getting NoSuchElementException error in my class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this class who is supposed open a file with a nr of questions in it with a nr of answer.
The problem is when it get's in that for to write in the ArrayList. I have tried all type of ArrayLists,LinkedLists, even vectors.
The first parts of the file, like the question and nr of answer, it takes it without any problem. But when i want to store those answers in a list so i can save that list in an object it won't work.
If anyone could help with this or knows a better method so save an unknown nr of string into an object list it would be epic.
The file format is:
A question,3,yes,no,maybe
Another question,4,yes,maybe,no,why not
my class:
public class GetSurvey {
public static String intrebare;
static int raspunsuri;
public static int i = 1;
static String holder;
//static String[] rasp = new String[250];
static List<String> rasp = new LinkedList<String>();
public static SurveyClass[] obj = new SurveyClass[250];
public static void loadSurvey()
{
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+File.separator+"Survey.dat");
if(!file.exists()){
try {
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
if(file.exists()){
try {
Scanner read = new Scanner(file);
read.useDelimiter(",");
while (read.hasNext())
{
intrebare = read.next();
String raspunsuri1 = read.next();
//Log.w("Date",String.valueOf(raspunsuri));
//obj[i].setNrRasp(raspunsuri);
for(int j = 0;j < 3;j++)
{
Log.w("Date",String.valueOf(j));
rasp.add(j,read.next());
}
String[] stringArr = rasp.toArray(new String[rasp.size()]);
Log.w("Date",stringArr[i]);
//obj[i].setRaspunsuri(rasp);
rasp.clear();
i++;
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
You're using read.next() 3 times inside your loop, so that means that you get past the end of the input, hence NoSuchElementException.
Use it only once and assign it to a local variable inside the loop, so you can use that value whenever you need it again later in the loop.
I'd suggest you should perform only one read.next() inside your while(read.hasNext()) Loop . Analyse the read element, perform the neccessary task and rerun the loop until while(read.hasNext()) fails. This way you can be sure you'll never perform a read beyond the size of your List.

JAVA. Searching a value and displays the data [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
'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.

Categories