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();
}
}
Related
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.
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 5 years ago.
Improve this question
I have imported both ArrayList and Integer. In my code I use the symbols in multiple places but I only get an error on one line.
Here are the import statements:
import java.util.ArrayList;
import java.lang.Integer;
Here are the pieces of code that compile properly:
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
private static void addPrime(ArrayList<Integer> primes)
{
int newNumber;
int x;
}
This piece of code return the symbol errors listed above:
while (lastValue < half)
{
addPrime(ArrayList<Integer> primes);
lastValue = primes.get(primes.size()-1);
}
I have done research on the problem but the only answer I can find is that the symbols were not imported properly at the beginning of the program.
A little background if you are not aware of already:
private static void addPrime(ArrayList<Integer> primes)
{
int newNumber;
int x;
}
is the method definition, where we define what the method will do for us. To make it do something for us we call the method passing the arguments, eg. addPrime(argument). Here you got to pass actual argument variable of type which you have defined in method definition.
So addPrime(primes) will work for you.
You don't need to specify the value type when calling a function. So instead of addPrime(ArrayList<Integer> primes); just simply do addPrime(primes);
The addPrime(...) function you have does not do anything in the example you gave.
import java.util.ArrayList;
import java.lang.Integer;
public class test
{
private static ArrayList<Integer> addPrime(ArrayList<Integer> primes, int num)
{
//Seems like you are trying to add primes to the list?
primes.add(num);
return primes;
}
public static void main(String[] args)
{
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
//Usage looks like
primes = addPrime(primes, 13);
// This will return 13 as the number 13 is the 5th element
System.out.println(primes.get(4));
}
}
Coded a bit better would be creating an object class so you do not keep passing around an array list
import java.util.ArrayList;
import java.lang.Integer;
public class IntArrList
{
private ArrayList<Integer> primes;
public IntArrList() {
primes = new ArrayList<Integer>();
}
public void addPrime(int num)
{
primes.add(num);
}
public int getPrimeListValue(int index)
{
return primes.get(index);
}
public ArrayList<Integer> getPrimeList()
{
return primes;
}
}
public class test
{
public static void main(String[] args)
{
IntArrList arrL = new IntArrList();
arrL.addPrime(2);
arrL.addPrime(3);
arrL.addPrime(5);
arrL.addPrime(7);
// This will return 7 as the number 7 is the 4th element
System.out.println(arrL.getPrimeListValue(3));
}
}
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 6 years ago.
Improve this question
I have the following class:
class A {
List<A> as;
}
I need to find max depth. For example, I can have this:
A firstA = new A();
A secondA = new A();
A thirdA = new A();
firstA.addA(secondA);
firstA.addA(thirdA);
secondA.addA(new A());
secondA.addA(new A());
I need to return 3.
I tried to do recursive method,
Using Java 8 streams:
class A {
List<A> as;
public int getDepth() {
return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
}
}
If you're not familiar with streams, this can be interpreted as 'add 1 to maximum depth of all children or 0 if there are no children'.
If you can't change A you can still use this by passing A into the method:
public class MyClass {
public static int getDepth(A a) {
return 1 + a.as.stream().mapToInt(MyClass::getDepth).max().orElse(0);
}
}
Recursive depth-computing:
public static int computeDepth(A a)
{
int maxDepth = 0;
for(A innerA : a.getAs())
{
int depth = computeDepth(innerA);
if(depth > maxDepth)
maxDepth = depth;
}
return maxDepth + 1;
}
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;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
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.
Improve this question
I am trying to create a vector method called readfromfile which would potentially read the input from a different text file. Why does it give an error?
Edit: Thanks for the help, I have edited the code and it works!
Looks like I was confusing parameters and methods! :P
Thanks guys :D
package cas.lab1.firsteclipsePackage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Vector;
public class FirstEclipseClass {
public static void main(String[] args) {
Vector input = new Vector();
input.add("A");
input.add("B");
input.add("C");
input.add("D");
printVectorElements(input, 3);
Vector<String> results = readFromFile();
}
public static void printVectorElements(Vector input, int count) {
for (int i = 0; i < count; i++) {
System.out.println(input.get(i));
}
}
public static Vector<String> readFromFile(){ //yeah I did confuse methods and parameters
Vector<String> result = new Vector<String>();
try{
File f = new File("input.txt");
Scanner s = new Scanner(f);
while(s.hasNextLine()) {
int i = s.nextInt();
if(i % 2 == 0)
result.add("Even");
else
result.add("Odd");
System.out.println(i);
}
s.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
return result;
}
}
I guess that you are confused here. From your method call, I see that you don't need to pass any parameters, and instead want a Vector back. So I suggest you to change this line:
public static readFromFile(Vector<String> results){
To this line:
public static Vector<String> readFromFile(){
First thing: you didn't specified the return type. You should have :
public static Vector<String> readFromFile()
if you do not need any parameters in the function.
Second, for future, you cannot have this same name in the function and as a function parameter