How to add data to a Java List? - java

Please see the code below with which I am trying to create a List. Can anybody tell me why this code does not work?
class materialsStore {
List<String> lista = new ArrayList<String>();
public void add(String antikeimena){
lista.add(antikeimena);
}
public List<String> getList(){
return lista;
}
}
public class finalState {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
materialsStore materialObj = new materialsStore();
String stoixeia = input.nextLine();
for(int i=1;i<=10;i++){
materialObj.add(stoixeia);
}
materialObj.saying();
}
}

You want to add to the list 10 times. So change your code to add input.nextLine() into the loop.
String stoixeia=null;
for(int i=0;i<10;i++){
stoixeia = input.nextLine();
materialObj.add(stoixeia);
}
As a sidenote , classes in java by convention start with upper case so it should be MaterialsStore.

If you pepper your code with System.out.println() statements to see what values are at various points, it may tell you what your problems are. Alternately, you can learn to set breakpoints in your IDE for debugging.

Related

how to take many multiple inputs in java and then perform a same operation on all those inputs

import java.util.Scanner;
class sexy
{
void even(String s)
{
for( int i=0;i<s.length();i++)
{
if((i==0) ||(i%2==0))
{
System.out.print(s.charAt(i));
}
}
}
void odd(String s)
{
for( int i=0;i<s.length() ; i++)
{
if(i%2!=0)
{
System.out.print(s.charAt(i));
}
}
}
}
class sassy
{
public static void main(String args[])
{
sexy se = new sexy();
Scanner scan = new Scanner(System.in);
int i=0,p;
p=scan.nextInt();
scan.nextLine();
String s;
while(i<p)
{
s = scan.nextLine();
se.even(s);
System.out.print(" ");
se.odd(s);
i++;
}
scan.close();
}
}
Now here i am able to take multiple inputs..and after every input i have to perform the operation on that particular input.. But I want to take multiple inputs at first and then perform the same operation on all the inputs using minimum variables..(if possible just one)
Well, it looks like you would either need a string array or a string arraylist.
You would use a string array if you knew how many inputs you would get, and an arraylist if you don't know how many inputs would be put in.
The code would look something like this:
ArrayList<String> lines = new ArrayList<>();
To put the values in, you would use lines.put(), and then lines.get(i) in your for loop to get values back out.
So to use it in your program, just add all the lines that the user inputs into the arraylist, and then traverse the arraylist to do the even and odd functions.
Good luck!

Why is the null error showing in my program; Stringtokenizer to array

This essentially is a small code I'm writting for practice that requires me to use StringTokenizer. I've done the same kind of programs before , but now when I store the strings in an array and try to print them it show's a null pointer exception. Any help?
import java.util.*;
public class board1
{
String key;
String m[];
//function to accept the sentence
void getsent()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a sentence terminated by'.' or '?'");
String take=in.nextLine();
StringTokenizer taken=new StringTokenizer(take);
int numtokens=taken.countTokens();
String m[]=new String[numtokens];
for(int i=0;i<m.length;i++)
{
m[i]=taken.nextToken();
}
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]);
}
}
// function to display
void display()
{
System.out.println("The words seperately right now are:");
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]+"\t");
System.out.println();
}
}
// main to get functions
public static void main(String args[])
{
board1 ob= new board1();
ob.getsent();
ob.display();
}
}
You're shadowing the variable m. Replace
String m[] = new String[numtokens];
with
m = new String[numTokens];
I think because you are shading properties. You have an array called m into which you are putting tokens in getSent, but display is using the m array defined in the class to which you haven't added anything.
Print out the size of m in display, this will show you that you are not adding anything to the property called m.

Java: ArrayList giving out a gibberish result

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.

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

How do I fill a String array in one method with data from another?

After meddling with arrays and countless google searches, I can't seem to find the answer.
public static void main(String args[]){
String[] names = new String[4]; //I want to fill this up with data from country
country(names);
System.out.println(names(0)) //I want this to display Madrid
}
public static void country(String[] names){
names[0] = "Madrid";
names[1] = "Berlin";
return;
}
I'm not sure if this explains what I'm trying to do.
You really have to work on java syntax. Your code is quite simple so it should work immediately, but you have to be careful with some details, here is a code which works fine:
public static void main(String args[]) {
String[] names = new String[4]; //I want to fill this up with data from country
country(names);
System.out.println(names[0]); //I want this to display Madrid
}
public static void country(String[] names) {
names[0] = "Madrid";
names[1] = "Berlin";
}
As you can see I use [ ] to access a value at a specific index in an array. I don't use any return in a void method neither.
You don't need to return the array in country method because java don't pass arguments on value (see http://javarevisited.blogspot.fr/2012/12/does-java-pass-by-value-or-pass-by-reference.html)
So I really advice you to read any tutorial you can find about java syntax to improve yourself for now.
Arrays are accessed using [], not (). You are also missing a semicolon in the printing statement.
Change:
System.out.println(names(0))
To:
System.out.println(names[0]); // use [] instead of () and add a semicolon
Also, the method country(String[] names) returns void so you don't need the return statement at the end of it (it's implied).
Here's how your code should look like:
public static void main(String args[]){
String[] names = new String[4]; //I want to fill this up with data from country
country(names);
System.out.println(names[0]); // use [] instead of () and add a semicolon
}
public static void country(String[] names){
names[0] = "Madrid";
names[1] = "Berlin";
}

Categories