Java: ArrayList giving out a gibberish result - java

The problem is as follows:
6 words are to be displayed on the screen. These words are chosen at random from a list. When I wrote the code, I didn't get any error, but when I ran it in eclipse, I got the following gibberish result in the console "package.wordsContainer#659e0bfd".
What did I do wrong?
public class wordsContainer {
Collection<String> wordList = new ArrayList<String>();
public void wordGroup1() {
wordList.add("Ant");
wordList.add("Almond");
wordList.add("Atom");
wordList.add("Affair");
wordList.add("Ample");
wordList.add("Blue");
wordList.add("Black");
wordList.add("Bronze");
wordList.add("Beauty");
wordList.add("Beautiful");
wordList.add("Batter");
wordList.add("Crazy");
}
public Collection<String> getRandomWords() {
wordGroup1();
LinkedList<String> wordLinkedList = new LinkedList<String>(wordList);
ArrayList<String> subList = new ArrayList<String>();
int i = 0;
while (i < 6) {
int index = (int) Math.random() * 10;
if (!subList.contains(wordLinkedList.get(index))) {
subList.add(wordLinkedList.get(index));
i++;
}
}
return subList;
}
}
public class wordsContainerTest {
public static void main(String[] args) {
wordsContainer list1 = new wordsContainer();
list1.wordGroup1();
System.out.println(list1);
System.out.println(list1.getRandomWords());
}
}

It's not gibberish, hexadecimal representation of the hash code of the object wordsContainer
That result is from the line
System.out.println(list1); //wordsContainer
Not from ArrayList.
In order to work properly you need to override toString method in your class wordsContainer
To understand what exactly is "package.wordsContainer#659e0bfd" read the answer I wrote long back.
https://stackoverflow.com/a/17878495/1927832
Apart from that, please follow java naming conventions, Class names starts with Capital letter.

System.out.println(list1); //wordsContainer
You can't print out objects directly, you will just print out the reference to the place in memory where the object is saved, which is that weird output you are getting. You have to override the toString() method in your object or print out the properties of the object that you want individually.

Related

How to remove a string from arrayList ending with another string?

Question : How to remove all Strings in rayList that end with the same Last Letter as lastLetter?
I write my code like this so i remove all string from ArrayList that has same end character as lastLetter
import java.util.*;
public class LastLetter
{
public static ArrayList<String> go(ArrayList<String> rayList, char lastLetter)
{
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i<rayList.size(); i++)
{
char last = rayList.set(i, rayList.get(raylist.size() - 1));
if(lastLetter == last)
result.add(rayList.remove(i));
}
return result;
}
}
I do not know if it is working or not and i do not understand how to make runner for this code please correct any problems from my code and make a runner so we can run this code properly.
My try to make runner:
import java.util.*;
class Runner
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("fred");
list.add("at");
list.add("apple");
list.add("axe");
list.add("bird");
list.add("dog");
list.add("kitten");
list.add("alligator");
list.add("chicken");
LastLetter h = new LastLetter();
System.out.println(h.go(list),"m");
}
}
Please make a proper runner for this code.
Thank you
You should not remove elements while iterating the ArrayList, for more information read this post the simplest solution will be using removeif
rayList.removeIf(val-val.endsWith(String.valueOf(lastLetter)));
I would also suggest to take string as argument instead of char
public static ArrayList<String> go(ArrayList<String> rayList, String lastLetter) {
rayList.removeIf(val-val.endsWith(lastLetter));
return result;
}
And since go is static method in LastLetter class you can call it by using class name
LastLetter.go(Arrays.asList("My name is faheem"), "m");

ArrayList getting reinitialized everytime the method is called

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

How to add to ArrayList in a For loop

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<>().

Returning the String at the index typed in by the user (ArrayList)

I'm trying to create a simple method. Basically, I want this method (called "returnIndex") to return the word at the ArrayList index number the user types in.
Example:
If the user types in "1", is should return whatever String is at index 1 in the ArrayList.
This is what I have so far:
public void returnIndex ()
{
Scanner in = new Scanner (System.in)
while (in.hasNextLine())
{
if (in.equals(1))
{
//return item at that index
}
}
}
I'm just not sure how to say "return the item at that index" in Java. Of course, I'll have to make the code work with any other number, not just '1'. But for now, I'm focusing on '1'. Not even sure if the in.equals(1) part is even 100% right.
My apologies if this question seems a little elementary. I'm still working on my Java. Just hints please, no complete answers. Thank you very much.
public String returnIndex(Scanner in, List<String> list) {
return list.get(in.nextInt());
}
Don't create new Scanners as it can cause subtle problems. Instead, create only one and keep using it. That means you should pass it into this function.
There's no need to use ArrayList when List will do (as it will here).
You need to make the function return String, not void, if you want it to return a String.
public static void main(String[] args) {
List<String> values = new ArrayList<String>();
values.add("One");
values.add("Two");
values.add("Three");
String result = getStringAtIndex(values);
System.out.println("The result:" + result);
}
public static String getStringAtIndex(List<String> list) {
Scanner scanner = new Scanner(System.in);
int index = 0;
index = scanner.nextInt();
return list.get(index-1);
}

Find and print the product of all the entries in array

Okay I have tried to write a simple Java code in BlueJ, that finds and prints the product of all the entries in data such as if data is {1,2,3,4} then the result will be 24.
And my code is below:
public class Product {
public static int[] product(int[] a) {
int [] s = new int[a.length];
for (int i =0; i< a.length; i++)
s[i] = a[i]*a[i];
return s; //the definition of your method...
}
public static void main(String[] args) {
//calling the method to seek if compiles
int[] results = Product.product(new int[] { 1,2,3,4 });
//printing the results
System.out.println(java.util.Arrays.toString(results));
}
}
The above code is giving me the square of each number, which is not what I want to have, somehow I have modify the code that the result will be 24 but I couldn't figure it out, anyone knows how to do it?
First of all, if you are first writing Java it is important to know that variable, function and class names are quite important. Please note that having Product.product() is not a good idea, since the function name is almost the same as the class name. Anyway, regarding your code. Your code is indeed returning the square of your input, what you would want is the following:
public class Product {
public static int getProduct(int[] input) {
int total = 1;
for (int v : input) {
total *= v;
}
return total;
}
}
This will return an integer value with the product of your input array. This also uses a for-each loop instead of a regular for-loop for readability. Also you don't need the index in this case. Good luck with it!
First, your product method needs to return an int rather than an int [].
You need to maintain the product as a variable. You can set it to 1 initially, and then multiply it by each element of the a array in turn; then you just return this value.

Categories