I have a sequence of information being randomly generated. I would like to save that information in a variable of some kind so that it can be recalled elsewhere. i think I want to use an ArrayList, but I'm not sure how to add the information while inside a for loop (which is where it is being created). The code I have is as follows:
public static ArrayList<String> phoneList
public static void main(String[] args){
Random randomNumber = new Random();
int howMany = randomNumber.nextInt(11);;
String holding;
for (int i=0; i < howMany; i++){
int itemRandNum = randomNumber.nextInt(11);//for all Item Categories
int priceRandNum = randomNumber.nextInt(11);//Prices for all categories
holding = phones[itemRandNum]+" $"+ priceOfPhones[priceRandNum];
//System.out.println(holding);
phoneList.add("holding"); //here is where I would like to add the information
//contained in "holding" to the "phoneList" ArrayList.
}
System.out.println(phoneList);
}
I am getting a NullPointerException. If an ArrayList is not the best thing to use here, what would be?
Any help you can give is appreciated.
public static void String Main(String[] args) suggests this doesn't have much to do with Android.
First, instantiate the list (Outside your for loop):
phoneList = new ArrayList<>(howMany); //Adding "howMany" is optional. It just sets the List's initial size.
Then, add the values:
for (int i = 0; i < howMany; i++) {
//...
phoneList.add(holding);
//Don't place holding in quotation marks, else you'll just add "holding" for every entry!
}
You get a NullPointerException because ArrayList phoneList is null since you didn't initialize it. Therefore write
public static ArrayList<String> phoneList = new ArrayList<>();
As it is you are just declaring the class ArrayList not instantiating it. it is necessary for all the time you want to use a class to create an instance of the same class and thats simple, just do:
public static ArrayList phoneList = new ArrayList() (if you are running older versions of java), otherwise use public static ArrayList phoneList = new ArrayList<>().
Related
Im making a small school project, keep in mind i'm a beginner. Im gonna make a small system that adds member numbers of members at a gym to an array. I need to make sure that people cant get the same member number, in other words make sure the same value doesnt appear on serveral index spots.
So far my method looks like this:
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
if(memberNr.equals(mNr)){
throw new IllegalArgumentException("The member is already in the system");
}
else{
memberNr[count++] = mNr;
}
}
While having a contructor and some attributes like this:
int[] memberNr;
int arraySize;
int count;
public TrainingList(int arraySize){
this.arraySize = arraySize;
this.memberNr = new int[arraySize];
}
As you can see i tried using equals, which doesnt seem to work.. But honestly i have no idea how to make each value unique
I hope some of you can help me out
Thanks alot
You can use set in java
Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
mport java.util.*;
public class Set_example
{
public static void main(String[] args)
{
// Set deonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("a");
hash_Set.add("b");
hash_Set.add("a");
hash_Set.add("c");
hash_Set.add("d");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
// Set deonstration using TreeSet
System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
}
}
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
//You need to loop through your array and throw exception if the incoming value mNr already present
for(int i=0; i<memberNr.length; i++){
if(memberNr[i] == mNr){
throw new IllegalArgumentException("The member is already in the system");
}
}
//Otherwise just add it
memberNr[count++] = mNr;
}
I hope the comments added inline explains the code. Let me know how this goes.
Hey you can’t directly comparing arrays (collection of values with one integer value)
First iterate the element in membernr and check with the integer value
I would like to model a graph, and to do so :
I have a class A that contains a LinkedList of instances of A and has a setter method associated :
class A {
private LinkedList<A> list;
[...]
public setList(LinkedList<A> l) {
this.list = l;
}
}
And in an other class NetA I have a method genCon that takes a LinkedList of instances of A then sets their list attribute to be a shuffled SubList of rlist :
static void genCon (LinkedList<A> rlist) {
for(int i=0; i<rlist.size(); i++) {
A temp = rlist.get(i);
LinkedList<A> slist = new LinkedList<A>(rlist.subList(0, rlist.size()));
temp.setList(slist);
}
}
Then genCon(rlist) is called in main, but altough all the objects of rlist should have their list initialized (and being equal to a shuffled version of rlist) some appear to be empty, with no consistent pattern (i.e. not every n or repeatable pattern), but completely at random.
At first I thought that A temp = rlist.get(i) was not giving me a shallow copy of the object at index i, but the check for identity with == returns true, so, if I am not mistaken that means that both variable hold the same reference and that should not be what is causing the issue?
Then I thought that it might be an optimization issue, maybe eclispe tries to do the operations in parallel and that somehow messes up the initialization at random?
I have tried to process step by step, but I can't seem to find where I messed up.
What did I miss?
Edit :
The main function looks like this :
public static void main(String[] args) {
LinkedList<A> a_list = generateAList(20);
genCon(a_list);
for(int i=0; i<a_list.size(); i++) {
System.out.println(a_list.get(i).toString());
}
}
a_list is correctly initialized. The issue happens in the following loop, when trying to print the objects.
Since it's only for testing main is located in the same class as genCon() atm.
generateAList() looks like this :
static public LinkedList<A> generateAList(int n) {
LinkedList<A> a_list = new LinkedList<A>();
for(int i=0; i<n; i++) {
ap_list.add(A.rand()); // A.rand() is just a static function that return an instance of A with randomly set values and an unitialized list.
}
return ap_list;
}
In my program, I want to create multiple threads in one of the methods where each thread has to run a specific method with a given input. Using Runnable, I have written this snippet.
class myClass {
public myClass() { }
public void doProcess() {
List< String >[] ls;
ls = new List[2]; // two lists in one array
ls[0].add("1"); ls[0].add("2"); ls[0].add("3");
ls[1].add("4"); ls[1].add("5"); ls[1].add("6");
// create two threads
Runnable[] t = new Runnable[2];
for (int i = 0; i < 2; i++) {
t[ i ] = new Runnable() {
public void run() {
pleasePrint( ls[i] );
}
};
new Thread( t[i] ).start();
}
}
void pleasePrint( List< String > ss )
{
for (int i = 0; i < ss.size(); i++) {
System.out.print(ss.get(i)); // print the elements of one list
}
}
}
public class Threadtest {
public static void main(String[] args) {
myClass mc = new myClass();
mc.doProcess();
}
}
Please note, my big code looks like this. I mean in one method, doProcess(), I create an array of lists and put items in it. Then I want to create threads and pass each list to a method. It is possible to define the array and lists as private class members. But, I want to do that in this way.
Everything seems to be normal, however, I get this error at calling pleasePrint():
error: local variables referenced from an inner class must be final or effectively final
pleasePrint( ls[i] );
How can I fix that?
The reason you are getting this error is straightforward and clearly mentioned - local variables referenced from an inner class must be final or effectively final. This is, in turn, because, the language specification says so.
Quoting Guy Steele here:
Actually, the prototype implementation did allow non-final variables
to be referenced from within inner classes. There was an outcry from
users, complaining that they did not want this! The reason was interesting: in order to support such variables, it was necessary to
heap-allocate them, and (at that time, at least) the average Java
programmer was still pretty skittish about heap allocation and garbage
collection and all that. They disapproved of the language performing
heap allocation "under the table" when there was no occurrence of the
"new" keyword in sight.
As far as your implementation goes, instead of using an array of list, I'd rather use a list of lists.
private final List<List<String>> mainList = new ArrayList<>();
You can create new lists and insert them into the main list in the constructor depending on the number of lists you want.
public ListOfLists(int noOfLists) {
this.noOfLists = noOfLists;
for (int i = 0; i < noOfLists; i++) {
mainList.add(new ArrayList<>());
}
}
You can then change your doProcess() method as follows:
public void doProcess() {
for (int i = 0; i < noOfLists; i++) {
final int index = i;
// Using Lambda Expression as it is much cleaner
new Thread(() -> {
System.out.println(Thread.currentThread().getName());
pleasePrint(mainList.get(index)); // Pass each list for printing
}).start();
}
}
Note: I used an instance variable named noOfLists to (as the name suggests) store the number of lists I need. Something as follows:
private final int noOfLists;
To populate the list, you could do:
mainList.get(0).add("1");
mainList.get(0).add("2");
mainList.get(0).add("3");
mainList.get(1).add("4");
mainList.get(1).add("5");
mainList.get(1).add("6");
// And so on...
And you'll get the output something as:
Thread-0
1
2
3
Thread-1
4
5
6
Hope this helps :)
First to that, you will get a NullPointerException here:
ls[0].add("1"); ls[0].add("2"); ls[0].add("3");
ls[1].add("4"); ls[1].add("5"); ls[1].add("6");
Before, yo must instantiate the lists:
ls[0] = new ArrayList<>();
ls[1] = new ArrayList<>();
About the compiler error, try to define the array as final. Change:
List< String >[] ls;
ls = new List[2]; // two lists in one array
By:
final List< String >[] ls = new List[2]; // two lists in one array
This is because you can't access to non-final (or effectively final) variables from a local class.
'ls' is effectively final but probably, since you have defined it in two lines, the compiler is not able to notice that.
I have written a method (part of a program) which takes in two int values(code below). One int value representing number of guys for whom java training is completed and another int value for guys for whom php training is completed. I expect the arraylist to grow with every function call. Example: First time I called the function with values (5,0). So the arrayList for java would be [5] and for php it would be [0] . Next time I call the function with values (2,3). The arrayList for java should now be [5][2] and sum should be 7. The the arraylist for php should be [0][3] ans sum should be 3. The problem with my code is that when I call the method for the second time, it wipes away the [5](value of first index from the first call) in the java arrayList and just takes the form of [2] and gives the sum 2(instead of the required 7). The arrayList is never growing. (same for the php arrayList) I am sure I am doing something conceptually wrong here . Please help Somehow, the way I have coded it, every function call seems to make a new arrayList and not growing the arrayList obtained from the previous call.
public class TrainingCamp {
public static int trainedJavaGuys ;
public static int trainedPHPGuys ;
public void trainedTroopsInCamp(int java,int php){
//System.out.println("********* Current Status of Training Camp ********* ");
ArrayList<Integer> trainingListJava = new ArrayList<>();
trainingListJava.add(java);
//System.out.println("---JavaARRAYLIST----"+trainingListJava);
trainedJavaGuys = sumList(trainingListJava);
ArrayList<Integer> trainingListPHP = new ArrayList<>();
trainingListPHP.add(php);
trainedPHPGuys = sumList(trainingListPHP);
//System.out.println("---phpARRAYLIST----"+trainingListPHP);
Calling it like this from another class:
TrainingCamp currentTrainingCamp = new TrainingCamp();
currentTrainingCamp.trainedTroopsInCamp(2, 0);
and next time the same two lines get executed with just the input params changed
The arraylists are reinitialized each time you call trainedTroopsInCamp() because they are declared within it.
You should make the arraylists member variables, so that they only get initialized once, in the class's constructor.
public class TrainingCamp {
public static int trainedJavaGuys ;
public static int trainedPHPGuys ;
// Declare once
ArrayList<Integer> trainingListJava;
ArrayList<Integer> trainingListPHP;
public TrainingCamp() {
// Initialize once
trainingListJava = new ArrayList<>();
trainingListPHP = new ArrayList<>();
}
public void trainedTroopsInCamp(int java,int php){
// Use everywhere
trainingListJava.add(java);
trainedJavaGuys = sumList(trainingListJava);
trainingListPHP.add(php);
trainedPHPGuys = sumList(trainingListPHP);
}
}
you're re-initializing the list references in the method call, so every time you call the method you're using a new (empty) list.
instead, try keeping the lists as member variables for your class, something like this:
class TrainingCamp {
private final List<Integer> javaTrained = new LinkedList<>();
private final List<Integer> phpTrained = new LinkedList<>();
public void trainedTroopsInCamp(int java,int php){
//System.out.println("********* Current Status of Training Camp ********* ");
javaTrained.add(java);
trainedJavaGuys = sumList(javaTrained);
phpTrained.add(php);
trainedPHPGuys = sumList(phpTrained);
}
...
}
I don't know if this is right, so I need your comments guys. I have an array of employee names. It will be displayed on the console, then will prompt if the user wants to insert another name. The name should be added on the end of the array(index 4) and will display again the array but with the new name already added. How do I do that? Btw, here's my code. And I'm stuck. I don't even know if writing the null there is valid.
public static void list() {
String[] employees = new String[5];
employees[0] = "egay";
employees[1] = "ciara";
employees[2] = "alura";
employees[3] = "flora";
employees[4] = null;
for(int i = 0; i < employees.length; i++) {
System.out.println(employees[i]);
}
}
public static void toDo() {
Scanner input = new Scanner(System.in);
System.out.println("What do you want to do?");
System.out.println("1 Insert");
int choice = input.nextInt();
if(choice == 1) {
System.out.print("Enter name: ");
String name = input.nextLine();
You can't, basically.
Arrays have a fixed size when they've been constructed. You could create a new array with the required size, copy all the existing elements into it, then the new element... or you could use a List<String> implementation instead, such as ArrayList<String>. I'd strongly advise the latter approach.
I suggest you read the collections tutorial to learn more about the various collections available in Java.
Also note that you've currently just got a local variable in the list method. You'll probably want a field instead. Ideally an instance field (e.g. in a class called Company or something similar) - but if you're just experimenting, you could use a static field at the moment. Static fields represent global state and are generally a bad idea for mutable values, but it looks like at the moment all your methods are static too...
Arrays are fixed in size. Once you declare you can not modify it's size.
Use Collection java.util.List or java.util.Set. Example ArrayList which is dynamic grow-able and backed by array.
If you really have to use arrays then you will have to increase the size of the array by using an intermediate copy.
String[] array = new String[employees.length + 1];
System.arraycopy(employees, 0, array, 0, employees.length);
array[employees.length] = newName;
employees = array;
However, the best way would be to use a List implementation.
It depends on whether the user can enter more than 4 employee names. If they can then using ArrayList is the better choice. Also the employees variable needs to be a static property of your class since being used in a static method.
private static String[] employees = new String[5];
static {
employees[0] = "egay";
employees[1] = "ciara";
employees[2] = "alura";
employees[3] = "flora";
employees[4] = null;
}
public static void list() {
for(int i = 0; i < employees.length; i++) {
System.out.println(employees[i]);
}
}
public static void addEmployeeName(String name, int index) {
employees[index] = name;
}
Here you are using static array which is fixed at the time of creation.I think you should use
java.util.Arraylist which will provide you facility of dynamic array.